Android_侧滑页面传值Fragment

来源:互联网 发布:mac适用的办公软件 编辑:程序博客网 时间:2024/06/05 15:09
第一:布局
<?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout    android:id="@+id/drawerlayout"    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="activity.example.com.drawerlayout.MainActivity">
       <FrameLayout             android:id="@+id/frameLayout"             android:layout_width="match_parent"             android:layout_height="match_parent"/>       <!--和drawerLayout配合需要配这两个属性       
            android:layout_gravity="left"            android:choiceMode="singleChoice" -->
<ListView android:id="@+id/listview" android:layout_width="200dp" android:layout_height="match_parent" android:layout_gravity="left" android:choiceMode="singleChoice" />
</android.support.v4.widget.DrawerLayout>
第二:Fragment中
public class Fragment1 extends Fragment{    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        TextView textView = new TextView(getActivity());        Bundle bundle = getArguments();        String text = bundle.getString("text");        textView.setText(text);        return textView;    }}

第三:代码
public class MainActivity extends AppCompatActivity {    private ListView listview;    private DrawerLayout drawerlayout;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        drawerlayout = (DrawerLayout) findViewById(R.id.drawerlayout);        listview = (ListView) findViewById(R.id.listview);        final ArrayList<String> list = new ArrayList<>();        for (int i = 0; i < 10; i++) {            list.add("DrawerLayout" + i);        }        ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, list);        listview.setAdapter(adapter);        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {            @Override            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {                Fragment1 fragment1 = new Fragment1();                Bundle bundle = new Bundle();                bundle.putString("text", list.get(i));                fragment1.setArguments(bundle);                getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragment1).commit();                //关闭侧滑页面                drawerlayout.closeDrawer(listview);            }        });    }}


原创粉丝点击