2015-05-09 6 views
1

Я пытаюсь получить доступ к TextViews в своем GridView и менять цвет фона, чтобы он менялся, когда я вызываю метод playSoE.Изменение элемента из gridview

ImageAdapter.java:

public class ImageAdapter extends BaseAdapter { 
    private Context mContext; 
    private int mCount; 
    public int[] mIds; //stores Ids from TextViews 

    public ImageAdapter(Context c, int count) { 
     mContext = c; 
     mCount = count; 
     mIds = new int[mCount]; 
    } 

    public int getCount() { 
     return mCount; 
    } 

    public Object getItem(int position) { 
     return null; 
    } 

    public long getItemId(int position) { 
     return 0; 
    } 

    // create a new ImageView for each item referenced by the Adapter 
    public View getView(int position, View convertView, ViewGroup parent) { 
     TextView textView; 

     if (convertView == null) { 
      // if it's not recycled, initialize some attributes 
      textView = new TextView(mContext); 
      mIds[position] = textView.getId(); //Id is stored into array 
      textView.setGravity(Gravity.CENTER); 
      textView.setLayoutParams(new GridView.LayoutParams(100, 100)); 

     } else { 
      textView = (TextView) convertView; 
     } 

     textView.setBackgroundColor(Color.RED); 
     textView.setText("" + position); 
     return textView; 
    } 

} 

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:scrollbars="none" 
    android:id="@+id/title_horizontalScrollView" 
    android:layout_margin="1dp" 
    android:fillViewport="false"> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     tools:context=".MainActivity" 
     android:id="@+id/relativelayout"> 

     <GridView 
      android:id="@+id/mGridView" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:columnWidth="90dp" 
      android:verticalSpacing="10dp" 
      android:horizontalSpacing="10dp" 
      android:stretchMode="columnWidth" 
      android:gravity="center" 
     /> 

    </RelativeLayout> 

</HorizontalScrollView> 

MainActivity.java:

public class MainActivity extends ActionBarActivity { 

    private boolean mIsPlaying; 
    private int primesLE; 
    private GridView mGridView; 

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

     mIsPlaying = false; 

     ViewGroup.LayoutParams layoutParams; 

     primesLE = 225; 
     int numOfColumns = (int)Math.round(Math.sqrt((double) primesLE)); 
     int numOfRows = (int)Math.ceil((double)primesLE/(double)numOfColumns); 

     GridView mGridView = (GridView) findViewById(R.id.mGridView); 
     layoutParams = mGridView.getLayoutParams(); 
     layoutParams.width = 150*numOfColumns; //this is in pixels 
     mGridView.setLayoutParams(layoutParams); 
     mGridView.setNumColumns(numOfColumns); 
     mGridView.setAdapter(new ImageAdapter(this, primesLE)); 

    } 



    @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(); 
     Log.d("Menu","Button Pressed"); 
     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     else if (id == R.id.action_status){ 
      if(mIsPlaying) { 
       mIsPlaying = false; 
       item.setIcon(R.drawable.ic_action_play); 
       item.setTitle("Play"); 
       playSoE(); 
      } 
      else { 
       mIsPlaying = true; 
       item.setIcon(R.drawable.ic_action_pause); 
       item.setTitle("Pause"); 
      } 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    private void playSoE(){ 
     int[] viewIds = ((ImageAdapter)mGridView.getAdapter()).mIds; //trying to get the Ids for the TextViews, doesn't work and crashes 
     for(int i = 0; i < primesLE;i++){ 
      Log.d("Getting view number",""+i); 
      mGridView.getAdapter(). 
       getItem(i).setBackgroundColor(Color.BLUE);//this doesn't work, crashes 
      mGridView.getChildAt(i).setBackgroundColor(Color.BLUE); //this doesn't work either, crashes 
     } 
    } 

} 

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.myname.sieveoferatosthenes" > 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

Я искал способы сделать это, но никто из них, похоже, не работает для меня.

ответ

0

Я решил свою проблему, mGridView был null все вместе. В MainActivity я использовал GridView mGridView = (GridView) findViewById(R.id.mGridView);, который был плохой кодировкой и не считал, что GridView был вложен в xml. Я изменил это

View v1 = findViewById(R.id.title_horizontalScrollView); 
View v2 = v1.findViewById(R.id.relativelayout); 
mGridView = (GridView) v2.findViewById(R.id.mGridView); 

И mGridView не нуль больше, то с помощью getChildAt(int position) бы получить меня TextView Я хотел (although some positions I still cannot access).

0

В вашем методе playSoE включить этот

<defined textview name here>.setBackgroundColor(Color.parseColor("#<hexadecimal color of your choice>")); 

Надеется, что помог.

EDIT: Я лично предпочитаю w3 найти шестнадцатеричные цвета http://www.w3schools.com/tags/ref_colorpicker.asp

что должно быть включено в XML-файле

<TextView 
      android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/whateveryouwantitsanid" 
       android:layout_weight="1" 
       /> 

ява

private TextView Texter;... 
//in your on create 
Texter = (TextView) findViewById(R.id.whateveryouwantitsanid); 
//where you want to change background 
Texter.setBackgroundColor(Color.parseColor("#yourhexcolorhere")); 

пс я не знаю, почему вы» re, помещая ваш идентификатор в массив

+0

Что вы имеете в виду '<определенное имя TextView здесь>'? У меня есть только «mGridView» и вам нужно выяснить, как получить один из TextViews внутри него. – user2361174

+0

Вы пытались определить текстовое представление отдельно (private textview .. (findviewbyid ...) и подключить текст в код выше? – Mazino

+0

Это не сработало, каждый раз, когда я создавал новый TextView, я взял его идентификатор и сохранил он в массив в ImageAdapter. В 'playSoE()' пытался сделать 'mGridView.getAdapter()' для получения массива. Но дал мне эту ошибку 'java.lang.NullPointerException: попытка вызвать виртуальный метод 'android. widget.ListAdapter android.widget.GridView.getAdapter() 'в ссылке нулевого объекта' – user2361174

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