2015-05-17 2 views
0

Пожалуйста, помогите мне, как добавить число пользовательских списков в список настраиваемых действий в текстовое поле в андроиде?Как добавить пользовательский список просмотров в панель действий в андроиде

Вот мой Activity Класс

public class DetaisRESTActivity extends Activity { 

String valueid,valueid1,valuename; 
public int count=0; 
JSONObject jsonobject; 
JSONArray jsonarray; 
public int listViewClickCounter=0; 

ListAdapterAddItems adapter; 

String restaurantmenuname,rastaurantname; 

ProgressDialog mProgressDialog; 
ArrayList<ListModel> arraylist; 
public static String RASTAURANTNAMEDETAILS = "RestaurantPizzaItemName"; 
public static String RASTAURANTRUPPEES = "RestaurantPizzaItemPrice"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
    setContentView(R.layout.activity_detais_rest); 
// getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.titlebar); 
    ActionBar actionBar = getActionBar(); 

    actionBar.setDisplayHomeAsUpEnabled(true); 
    actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000"))); 

    LayoutInflater mInflater = LayoutInflater.from(this); 

    View mCustomView = mInflater.inflate(R.layout.titlebar, null); 
    TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789); 
    Toast.makeText(DetaisRESTActivity.this,listViewClickCounter, Toast.LENGTH_LONG).show(); 
    mTitleTextView.setText(listViewClickCounter); 

    ImageButton imageButton = (ImageButton) mCustomView 
      .findViewById(R.id.imageButton2); 
    imageButton.setOnClickListener(new View.OnClickListener() { 


     @Override 
     public void onClick(View view) { 
      Toast.makeText(getApplicationContext(), "Refresh Clicked!", 
        Toast.LENGTH_LONG).show(); 
      Intent i=new Intent(DetaisRESTActivity.this,QuentityActivity.class); 
      startActivity(i); 
     } 
    }); 

    actionBar.setCustomView(mCustomView); 
    actionBar.setDisplayShowCustomEnabled(true); 
    Intent intent = getIntent(); 
    // get the extra value 
    valuename = intent.getStringExtra("restaurantmenuname"); 
    valueid = intent.getStringExtra("restaurantmenunameid"); 
    valueid1 = intent.getStringExtra("idsrestaurantMenuId5"); 

    Log.i("valueid",valueid); 
    Log.i("valuename",valuename); 
    Log.i("valueid1",valueid1); 

    new DownloadJSON().execute(); 
} 


// DownloadJSON AsyncTask 
private class DownloadJSON extends AsyncTask<Void,Void,Void> { 

    @Override 

    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Create a progressdialog 
     mProgressDialog = new ProgressDialog(DetaisRESTActivity.this); 
     // Set progressdialog title 
     mProgressDialog.setTitle("Android JSON Parse Tutorial"); 
     // Set progressdialog message 
     mProgressDialog.setMessage("Loading..."); 
     mProgressDialog.setIndeterminate(false); 
     // Show progressdialog 
     mProgressDialog.show(); 
     Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     // Create an array 
     arraylist = new ArrayList<ListModel>(); 
     // Retrieve JSON Objects from the given URL address 
     // Log.i("123",value1); 
     jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + ""); 



     try { 

      // Locate the array name in JSON 
      jsonarray = jsonobject.getJSONArray("RestaurantMenItems"); 
      Log.i("1234",""+jsonarray); 

      for (int i = 0; i < jsonarray.length(); i++) { 

       jsonobject = jsonarray.getJSONObject(i); 


       ListModel sched = new ListModel(); 
       sched.setProductName(jsonobject.getString("RestaurantPizzaItemName")); 

       sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice")); 

       arraylist.add(sched); 

      } 
     } catch (JSONException e) { 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void args) { 
     // Locate the listview in listview_main.xml 
final ListView listview = (ListView) findViewById(R.id.listViewdetails); 

     adapter = new ListAdapterAddItems(); 

     listview.setAdapter(adapter); 
     // Close the progressdialog 
     mProgressDialog.dismiss(); 

     listview.setOnItemClickListener(new AdapterView.OnItemClickListener() 
     { 
      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) 
      { 

       // Get Person "behind" the clicked item 
       ListModel p =(ListModel)listview.getItemAtPosition(position); 
       // Log the fields to check if we got the info we want 
       Log.i("SomeTag", "Persons: " + p.getCount()); 
       Log.i("SomeTag", "Persons name: " + p.getProductName()); 
       Log.i("SomeTag", "Ruppees: " + p.getPrice()); 

       count++; 
       String countString=String.valueOf(count); 
       Toast toast = Toast.makeText(getApplicationContext(), 
         "Item " + (position + 1), 
         Toast.LENGTH_SHORT); 
       toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); 
       toast.show(); 

       Toast.makeText(getBaseContext(), 
         countString, Toast.LENGTH_LONG).show(); 

      } 
     }); 



    } 
} 

//========================== 
class ListAdapterAddItems extends ArrayAdapter<ListModel> 
{ 
    ListAdapterAddItems(){ 
     super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist); 
     //imageLoader = new ImageLoader(MainActivity.this); 
    } 
    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     final ViewHolder holder; 
     if(convertView == null){ 
      LayoutInflater inflater = getLayoutInflater(); 
      convertView = inflater.inflate(R.layout.cartlistitem, null); 
      holder = new ViewHolder(convertView); 
      convertView.setTag(holder); 
     }else{ 
      holder = (ViewHolder)convertView.getTag(); 
     } 
     holder.populateFrom(arraylist.get(position)); 
     return convertView; 
    } 
} 

class ViewHolder { 
    public TextView restaurantname = null; 
    public TextView ruppees = null; 


    ViewHolder(View row) { 
     restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant); 
     ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant); 

    } 

    // Notice we have to change our populateFrom() to take an argument of type "Person" 
    void populateFrom(ListModel r) { 
     restaurantname.setText(r.getProductName()); 
     ruppees.setText(r.getPrice()); 

    } 


} 














    //============================================================= 






@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_detais_rest, menu); 
    return true; 
} 
+0

Итак, вы хотите, чтобы каждый раз, когда пользователь нажимает на элемент списка списка, вы изменяете заголовок панели действий и затем изменяете заголовок панели действий? –

+0

yes @Andy Joyce –

+0

Вы делаете это внутри действия или фрагмента? –

ответ

0

ИТАК, прежде всего объявить переменную экземпляра, чтобы сохранить количество щелчков.

public int listViewClickCounter; 

на вашем ListView OnClick увеличивает счетчик и вызвать метод BAR изменить действие

yourListView.setOnItemClickListener(new OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, 
       long id) { 

      listViewClickCounter++ 
      changeActionBarTitle(); 
     } 
    }); 

Затем реализовать метод бара изменения действий. Вы сказали, что у вас есть собственный вид, так что вы, возможно, придется изменить немного

public void changeActionBarTitle() { 

myActionBarCustomTitle.setText("number of clicks =" + String.valueOf(listViewClickCounter)); 
+0

Спасибо, Но ваш код не работает в моей деятельности –

+0

Можете ли вы отредактировать вопрос, чтобы включить код –

+0

проверить его мой код –

0

Добавить глобальную int переменную в класс, и в вашем ListViewonItemClickListener приращению этой переменной ++1 и получить ссылку на ваш TextVie ш и использовать TextView.setText(String.ValueOf(that_int_variable));

EDIT

Глядя на ваш код все выглядит отлично, только некоторые механизмы, прежде всего позвольте mTitleTextView быть Glob al TextView объект только в oncreate, чтобы вы могли ссылаться на него. Вы видите, какая переменная, которую вы объявляете в методе, живет во время вызова метода. или вы можете получить ActionBar и использовать findViewById() так что ваш код должен выглядеть следующим образом

String valueid,valueid1,valuename; 
public int count=0; 
JSONObject jsonobject; 
JSONArray jsonarray; 
public int listViewClickCounter=0; 
TextView mTitleTextView; // this is the edit. you add the textview 
ListAdapterAddItems adapter; 
String restaurantmenuname,rastaurantname; 
//then the rest will continue, i skipped all that 

и вместо того, чтобы текст сразу в TextView установить его, когда элемент нажимали

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() 
    { 
     @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) 
     { 

      // Get Person "behind" the clicked item 
      ListModel p =(ListModel)listview.getItemAtPosition(position); 
      // Log the fields to check if we got the info we want 
      Log.i("SomeTag", "Persons: " + p.getCount()); 
      Log.i("SomeTag", "Persons name: " + p.getProductName()); 
      Log.i("SomeTag", "Ruppees: " + p.getPrice()); 

      count++; 
      String countString=String.valueOf(count); 
      Toast toast = Toast.makeText(getApplicationContext(), 
        "Item " + (position + 1), 
        Toast.LENGTH_SHORT); 
      toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); 
      toast.show(); 

      Toast.makeText(getBaseContext(), 
        countString, Toast.LENGTH_LONG).show(); 
      mTitleTextView.setText(countString); 

     } 
    }); 

Это все, что вам нужно сделать, и вы не используете эту переменную intlistViewClickCounter

+0

Спасибо, Но ваш код не работает в моей деятельности –

+0

публикуйте свою деятельность Сэр, @ sundersharma – Elltz

Смежные вопросы