2016-08-13 2 views
1

Я могу стрелять намерениями на свою кнопку. и я хочу получить позицию или идентификатор определенной кнопки просмотра и передать намерение. так PLS помочь? Мои данные списка - это анализ из веб-url.Как получить позицию позиции из пользовательского gridview, установленного в классе адаптера?

BaseAdapter класса // как я могу получить положение кнопки и огонь намерение

public class ListAdapter extends BaseAdapter{ 

LayoutInflater inflater; 

Context context; 

ArrayList<HashMap<String, String>> contactList= new ArrayList<HashMap<String, String>>(); 

public ListAdapter(Context context) { 

    this.context=context; 

     inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); 
} 

@Override 
public int getCount() { 
    return 0; 
} 

@Override 
public Object getItem(int i) { 
    return null; 
} 

@Override 
public long getItemId(int i) { 
    return 0; 
} 

@Override 
public View getView(final int i, View view, final ViewGroup viewGroup) { 


    ViewHolder holder; 
    if(view == null) { 
     // Inflate and initialize your layout 
     view = inflater.inflate(R.layout.list, viewGroup, false); 
     holder = new ViewHolder(); 
     holder.addsql = (Button) view.findViewById(R.id.addsql); 

     holder.addsql.setTag(new Integer(i)); 





     // etc, etc... 
     view.setTag(holder); 
    } 
    else { 
     holder = (ViewHolder) view.getTag(); 
    } 



    holder.addsql.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      Log.d("position is" , ""+view.getTag()); 
      //Integer i = (Integer)view.getTag(); 
      Toast.makeText(view.getContext(), "helllllo", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
    return view; 
} 


} 

class ViewHolder { 
    TextView date; 
    TextView title; 
    TextView price; 
    Button addsql; 
    Button button; 
    int position; 
} 

// эти две кнопки, где я установить намерения двигаться другой деятельности. XML файл

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="" 
    android:id="@+id/date" 
    android:layout_gravity="center_horizontal" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:id="@+id/title" 
    android:layout_gravity="center_horizontal" /> 



<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="" 
    android:id="@+id/price" 
    android:layout_gravity="center_horizontal" /> 

<Button 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="ADD SQL" 
    android:id="@+id/addsql" 
    android:focusable="false" 
    android:layout_gravity="center_horizontal" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="New Button" 
    android:id="@+id/button" 
    android:layout_gravity="center_horizontal" /> 

</LinearLayout> 

// В этом упражнении я анализирую данные из веб-адрес через JSON.

_MainActivity.java_ 

public class MainActivity extends Activity { 

private ProgressDialog pDialog; 

// URL to get contacts JSON 
private static String url = "http://www.goteso.com/projects/dinvinguide/api/get_magazines.php"; 

// JSON Node names 




private static final String ID = "id"; 
private static final String MID = "magazine_id"; 
private static final String Date="date"; 
private static final String Title= "title"; 
private static final String CoverPic = "cover_pic"; 
private static final String Price= "price"; 
private static final String Description = "description"; 
private static final String Halfpdf = "light_pdf"; 
private static final String Fullpdf = "full_pdf"; 
private static final String Ios = "ios_app_purchase_id"; 
private static final String Aos = "android_purchase_id"; 

// contacts JSONArray 
JSONArray contact ; 
ListView lv; 
Button addsql; 
    ListAdapter list; 
//Context con; 

// Hashmap for ListView 
    ArrayList<HashMap<String, String>> contactList; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    contactList=new ArrayList<HashMap<String,String>>(); 
    lv=(ListView)findViewById(R.id.listView); 
    list = new com.example.gurcharan.jsondemoo.ListAdapter(this); 



    // Calling async task to get json 
    new GetContacts().execute(); 


} 

/** 
* Async task class to get json by making HTTP call 
* */ 
private class GetContacts extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Showing progress dialog 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Please wait..."); 
     pDialog.setCancelable(false); 
     pDialog.show(); 

    } 

    @Override 
    protected Void doInBackground(Void... arg0) { 
     // Creating service handler class instance 
     ServiceHandler sh = new ServiceHandler(); 

     // Making a request to url and getting response 
     String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); 

     Log.d("Response: ", "> " + jsonStr); 

     if (jsonStr != null) { 
      try { 

       contact=new JSONArray(jsonStr); 
       //JSONObject jsonObj = new JSONObject(jsonStr); 

       // Getting JSON Array node 
       // String contacts = jsonObj.getJSONArray(TAG_CONTACTS); 
       String str=contact.getString(0); 
       // looping through All Contacts 
       for (int i = 0; i < contact.length(); i++) { 
        JSONObject c = contact.getJSONObject(i); 

        String id = c.getString(ID); 
        String date = c.getString(Date); 
        String title = c.getString(Title); 
        String cover_pic = c.getString(CoverPic); 
        String price = c.getString(Price); 

        String description = c.getString(Description); 
        String light_pdf = c.getString(Halfpdf); 
        String full_pdf = c.getString(Fullpdf); 
        String ios_app_purchase_id = c.getString(Ios); 
        String android_purchase_id = c.getString(Aos); 


        // tmp hashmap for single contact 
        HashMap<String, String> contact = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 

        contact.put(Date, date); 
        contact.put(Title, title); 
        contact.put(Price, price); 
        //contact.put(CoverPic, cover_pic); 

        // adding contact to contact list 
        contactList.add(contact); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     /** 
     * Updating parsed JSON data into ListView 
     * 
     * */ 



     ListAdapter adapter = new SimpleAdapter(
       MainActivity.this, contactList, 
       R.layout.list, new String[] { Date, Title, 
       Price }, new int[] { R.id.date, 
       R.id.title, R.id.price }); 



       lv.setAdapter(adapter); 




    } 


} 


} 

// здесь вид списка задается _main_activity.xml_

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.example.gurcharan.jsondemoo.MainActivity"> 


<ListView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/listView" 
    android:layout_centerVertical="true" 
    android:layout_centerHorizontal="true" /> 
</RelativeLayout> 

ответ

0

Мы можем использовать класс ViewHolder в BaseAdapter и не использовать SimpleAdapter. Мы должны использовать этот адаптер, который мы определяем для расширения класса

0

добавить этот класс в адаптере:

private class OnButtonClick implements View.OnClickListener { 
    /** 
    * @param pos it is your current position 
    */ 
    int pos; 

    public OnButtonClick(int pos) { 
     this.pos = pos; 
    } 

    @Override 
    public void onClick(View view) { 
     // intent from here 
    } 
} 

затем определяют кнопку клик событие, как это:

holder.yourbutton.setOnClickListener(new OnButtonClick()); 
+0

Это не работает, пожалуйста, прочитайте полный код, который я обновляю снова. –

+0

Брат, которого вы установили, адаптер является простым адаптером. и вы добавили код адаптера BaseAdapter. Как это может совпадать? –

+0

Спасибо, сэр, я получил его @ Dharvik shah –