java - 单击回收器查看项目时导航至 Activity

标签 java android

大家好,我创建了一个带有回收器 View 的抽屉导航,现在我想在按下第一个项目时转到另一个 Activity ,并在按下第二个项目时转到另一个 Activity ,依此类推。这是我的适配器

     import android.content.Context;
     import android.support.v7.widget.RecyclerView;
     import android.view.LayoutInflater;
     import android.view.View;
     import android.view.ViewGroup;
     import android.widget.ImageView;
     import android.widget.TextView;
     import android.widget.Toast;


    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private static final int TYPE_HEADER = 0;  // Declaring Variable to Understand which View is being worked on
    // IF the viaew under inflation and population is header or Item
    private static final int TYPE_ITEM = 1;

    private String mNavTitles[]; // String Array to store the passed titles Value from MainActivity.java
    private int mIcons[];       // Int Array to store the passed icons resource value from MainActivity.java

    private String name;        //String Resource for header View Name
    private int profile;        //int Resource for header view profile picture
    private String email;       //String Resource for header view email
    Context context;


    // Creating a ViewHolder which extends the RecyclerView View Holder
    // ViewHolder are used to to store the inflated views in order to recycle them

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        int Holderid;

        TextView textView;
        ImageView imageView;
        ImageView profile;
        TextView Name;
        TextView email;
        Context contxt;


        public ViewHolder(View itemView,int ViewType,Context c) {                 // Creating ViewHolder Constructor with View and viewType As a parameter
            super(itemView);
            contxt = c;
            itemView.setClickable(true);
            itemView.setOnClickListener(this);
            // Here we set the appropriate view in accordance with the the view type as passed when the holder object is created

            if(ViewType == TYPE_ITEM) {
                textView = (TextView) itemView.findViewById(R.id.rowText); // Creating TextView object with the id of textView from item_row.xml
                imageView = (ImageView) itemView.findViewById(R.id.rowIcon);// Creating ImageView object with the id of ImageView from item_row.xml
                Holderid = 1;                                               // setting holder id as 1 as the object being populated are of type item row
            }
            else{


                Name = (TextView) itemView.findViewById(R.id.name);         // Creating Text View object from header.xml for name
                email = (TextView) itemView.findViewById(R.id.email);       // Creating Text View object from header.xml for email
                profile = (ImageView) itemView.findViewById(R.id.circleView);// Creating Image view object from header.xml for profile pic
                Holderid = 0;                                                // Setting holder id = 0 as the object being populated are of type header view
            }



        }


        @Override
        public void onClick(View v) {

            Toast.makeText(contxt,"The Item Clicked is: "+getPosition(), Toast.LENGTH_SHORT).show();

        }
    }



    MyAdapter(String Titles[],int Icons[],String Name,String Email, int Profile,Context passedContext){ // MyAdapter Constructor with titles and icons parameter
        // titles, icons, name, email, profile pic are passed from the main activity as we
        mNavTitles = Titles;                //have seen earlier
        mIcons = Icons;
        name = Name;
        email = Email;
        profile = Profile;                     //here we assign those passed values to the values we declared here
        this.context = passedContext;

        //in adapter



    }



    //Below first we ovverride the method onCreateViewHolder which is called when the ViewHolder is
    //Created, In this method we inflate the item_row.xml layout if the viewType is Type_ITEM or else we inflate header.xml
    // if the viewType is TYPE_HEADER
    // and pass it to the view holder

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == TYPE_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false); //Inflating the layout

            ViewHolder vhItem = new ViewHolder(v,viewType,context); //Creating ViewHolder and passing the object of type view

            return vhItem; // Returning the created object

            //inflate your layout and pass it to view holder

        } else if (viewType == TYPE_HEADER) {

            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header,parent,false); //Inflating the layout

            ViewHolder vhHeader = new ViewHolder(v,viewType,context); //Creating ViewHolder and passing the object of type view

            return vhHeader; //returning the object created


        }
        return null;

    }

    //Next we override a method which is called when the item in a row is needed to be displayed, here the int position
    // Tells us item at which position is being constructed to be displayed and the holder id of the holder object tell us
    // which view type is being created 1 for item row
    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
        if(holder.Holderid ==1) {                              // as the list view is going to be called after the header view so we decrement the
            // position by 1 and pass it to the holder while setting the text and image
            holder.textView.setText(mNavTitles[position - 1]); // Setting the Text with the array of our Titles
            holder.imageView.setImageResource(mIcons[position -1]);// Settimg the image with array of our icons
        }
        else{

            holder.profile.setImageResource(profile);           // Similarly we set the resources for header view
            holder.Name.setText(name);
            holder.email.setText(email);
        }
    }

    // This method returns the number of items present in the list
    @Override
    public int getItemCount() {
        return mNavTitles.length+1; // the number of items in the list will be +1 the titles including the header view.
    }


    // Witht the following method we check what type of view is being passed
    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

}

主要 Activity

 import android.support.v7.app.ActionBarActivity; 
 import android.os.Bundle;
 import android.view.GestureDetector;
 import android.view.Menu;
 import android.view.MenuItem;


 import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

//First We Declare Titles And Icons For Our Navigation Drawer List View
//This Icons And Titles Are holded in an Array as you can see

String TITLES[] = {"Saida","Jdeede","Dawra","Hamra","Jounieh"};
int ICONS[] = {R.drawable.a,R.drawable.a,R.drawable.a,R.drawable.a,R.drawable.a};

//Similarly we Create a String Resource for the name and email in the header view
//And we also create a int resource for profile picture in the header view

String NAME = "Mahmoud Mrad";
String EMAIL = "Info.Mrad4Tech@gmail.com";
int PROFILE = R.drawable.aka;

private Toolbar toolbar;                              // Declaring the Toolbar Object

RecyclerView mRecyclerView;                           // Declaring RecyclerView
RecyclerView.Adapter mAdapter;                        // Declaring Adapter For Recycler View
RecyclerView.LayoutManager mLayoutManager;            // Declaring Layout Manager as a linear layout manager
DrawerLayout Drawer;                                  // Declaring DrawerLayout

ActionBarDrawerToggle mDrawerToggle;                  // Declaring Action Bar Drawer Toggle




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

/* Assinging the toolbar object ot the view
and setting the the Action bar to our toolbar
 */
    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);




    mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View

    mRecyclerView.setHasFixedSize(true);                            // Letting the system know that the list objects are of fixed size

    mAdapter = new MyAdapter(TITLES,ICONS,NAME,EMAIL,PROFILE,this);       // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
    // And passing the titles,icons,header view name, header view email,
    // and header view profile picture

    mRecyclerView.setAdapter(mAdapter);                              // Setting the adapter to RecyclerView

    final GestureDetector mGestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {

        @Override public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

    });


    mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
            View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());



            if(child!=null && mGestureDetector.onTouchEvent(motionEvent)){
                Drawer.closeDrawers();
                Toast.makeText(MainActivity.this,"The Item Clicked is: "+recyclerView.getChildPosition(child), Toast.LENGTH_SHORT).show();

                return true;

            }

            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

        }
    });


    mLayoutManager = new LinearLayoutManager(this);                 // Creating a layout Manager

    mRecyclerView.setLayoutManager(mLayoutManager);                 // Setting the layout Manager


    Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);        // Drawer object Assigned to the view
    mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
            // open I am not going to put anything here)
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            // Code here will execute once drawer is closed
        }



    }; // Drawer Toggle Object Made
    Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
    mDrawerToggle.syncState();               // Finally we set the drawer toggle sync State

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

希望你能帮助我谢谢

最佳答案

在这里你正在监听点击。我在我的回收器 View 适配器中有它,但你在 Activity 中有它

mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {

在此处添加

 @Override
            public void onClick(View view, int position) {

            switch (position) {

            case 0:

            //code

            //then close the drawer
            mRecyclerView.closeDrawer(RecyclerView);


            break;

           case1, case2, case3 etc

          )
    }

关于java - 单击回收器查看项目时导航至 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32595337/

相关文章:

java - 在不同包中扩展 WebSecurityConfigurerAdapter 类时,自定义安全性不起作用

java - 监控Java内部对象和内存使用情况

android - Asmack 18 连接 : google. com :5222 Exception: Could not connect to talk. google.com 远程服务器超时

android - NestedScrollView 内的子级未覆盖整个屏幕高度

android - 获取 Android 所有者的全名。 Ice Cream Sandwich 之前

java - Jprofiler Agent安装报错Centos 7

java - 如何调整单个 JTable 列的大小而不影响其他表列

java - 无法解析符号。无法将位置数据添加到图像的 EXIF。

java - 无法纠正我的 java 程序

android - 更改 Activity 时如何更改默认动画?