android Wait between GridView updates - java

I have a GridView of TextViews, I want to iterate though each TextView, change it's background, wait for 1 second, and go to the next TextView and do the same thing.
First start off with none of the TextViews being colored
Then I want to color the first TextView
Now I want to wait for one second...
and afterwards.
And repeat with the remaining TextViews.
The problem is, MainActivity.playSoE(), the method that does updating of the grid, uses notifyDataSetChanged() to update the GridView. Which makes threading more of an issue. Everything I've tried either causes an Exception or freezes everything and skips the intermediate steps until the whole Grid is colored. I've tried using Activity.runOnUiThread(), wait(), Thread.sleep() and tried making a new Thread but none of these has worked for me. I
And to clarify, I want to be able to communicate with the rest of the app while the Grid is being colored, I don't want the entire app freezing on me.
MainActivity.java:
public class MainActivity extends ActionBarActivity {
private boolean mIsPlaying;
private int primesLE;
private GridView mGridView;
private ImageAdapter mAdapter;
private Thread mThread;
private void dataVisualization(){
int numOfColumns = (int)Math.round(Math.sqrt((double) primesLE));
//int numOfRows = (int)Math.ceil((double)primesLE/(double)numOfColumns);
ViewGroup.LayoutParams layoutParams;
layoutParams = mGridView.getLayoutParams();
layoutParams.width = 150*numOfColumns; //this is in pixels
mGridView.setLayoutParams(layoutParams);
mGridView.setNumColumns(numOfColumns);
mAdapter = new ImageAdapter(this, android.R.layout.simple_list_item_1, primesLE);
mGridView.setAdapter(mAdapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIsPlaying = false;
primesLE = 0;
View relativeLayout = findViewById(R.id.relativeLayout);
View title_horizontalScrollView = relativeLayout.findViewById(R.id.title_horizontalScrollView);
View dataLayout = title_horizontalScrollView.findViewById(R.id.dataLayout);
mGridView = (GridView) dataLayout.findViewById(R.id.mGridView);
dataVisualization();
View inputLayout = relativeLayout.findViewById(R.id.inputLayout);
final EditText inputEditText = (EditText)inputLayout.findViewById(R.id.inputEditText);
inputEditText.setOnKeyListener(new EditText.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
InputMethodManager inputManager = (InputMethodManager) MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(inputEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
try {
primesLE = Integer.parseInt(inputEditText.getText().toString());
} catch(NumberFormatException nfe) {
inputEditText.setText("Try again");
primesLE = 0;
}
if(primesLE < 0)
primesLE = 0;
dataVisualization();
Toast.makeText(MainActivity.this, inputEditText.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
inputEditText.setOnClickListener(new EditText.OnClickListener() {
#Override
public void onClick(View v) {
inputEditText.getText().clear();
}
});
}
#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;
}
private void playSoE(){
for(int i = 0; i < primesLE; i++) {
mAdapter.setPositionColor(i, 0xffff0000 + 0x100 * i); //calls notifyDataSetChanged()
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
}, 1000);
}
}
#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);
}
}
ImageAdapter.java:
public class ImageAdapter extends ArrayAdapter {
private Context mContext;
private int mCount;
private boolean setBlueBackground = false;
private int[] gridColors;
public ImageAdapter(Context c, int resource, int count) {
super(c, resource);
mContext = c;
mCount = count;
gridColors = new int[mCount];
Arrays.fill(gridColors,Color.LTGRAY);
}
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);
textView.setGravity(Gravity.CENTER);
textView.setLayoutParams(new GridView.LayoutParams(100, 100));
} else {
textView = (TextView) convertView;
}
textView.setBackgroundColor(gridColors[position]);
textView.setText("" + position);
return textView;
}
public void setPositionColor(int position, int color) {
gridColors[position] = color;
notifyDataSetChanged();
}
}
activity_main.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:id="#+id/relativeLayout"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/inputLayout"
android:layout_alignParentTop="true"
android:background="#a9a9a9"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:id="#+id/textView"
android:text="All primes less than\n or equal to this number:"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
android:focusable="true" android:focusableInTouchMode="true"
android:layout_width="0px" android:layout_height="0px"
android:inputType="numberSigned"/>
<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="#+id/autotext"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:nextFocusUp="#id/autotext" android:nextFocusLeft="#id/autotext"
android:inputType="numberSigned" android:imeOptions="actionDone"
android:layout_gravity="center_vertical" android:gravity="center_vertical"
android:layout_centerVertical="true" android:layout_toEndOf="#+id/textView"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/inputEditText"
android:layout_centerVertical="true"
android:layout_alignEnd="#+id/autotext"
android:layout_toEndOf="#+id/textView" />
</RelativeLayout>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/inputLayout"
android:id="#+id/title_horizontalScrollView"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/dataLayout"
>
<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"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</HorizontalScrollView>
</RelativeLayout>
menu_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_status"
android:icon="#drawable/ic_action_play"
android:title="Play"
app:showAsAction="always"/>
<item android:id="#+id/action_stop"
android:icon="#drawable/ic_action_stop"
android:title="Stop"
app:showAsAction="always"/>
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>

Ultimately you should switch to using a RecyclerView with a GridLayoutManager. The RecyclerView offers very flexible methods for updating the UI. In your case, notifyItemChanged(int position) would efficiently update one single TextView. Find out more here.

You can use Handler to delay and perform your action
Edited
for(int i = 0; i < primesLE; i++) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mAdapter.setPositionColor(i, 0xffff0000 + 0x100 * i);
notifyDataSetChanged();
}
}, 1000);
}
This will execute for 1 second and will update the data

Related

New RecyclerView item on click of button

I am a bit new to Android so forgive for any shortcomings.
I have a FloatingActionButton in the activity_main.xml and whenever it is clicked I want it to take me to a new activity with two EditText fields and there is another FAB there.
What I want to do is that whenever text is input and the FAB in the activity_new_goal.xml is pressed it should create a RecyclerView with the text in the #+id/edit_goalTitle text.
It is showing me error of incompatible types in return data; and showing cannot resolve method getData() in the MainActivity.java
Here's my code:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private RVAdapter adapter;
private RecyclerView recyclerView;
private EditText editGoalTitle;
private String stringGoalTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), (Toolbar) findViewById(R.id.app_bar));
recyclerView = (RecyclerView) findViewById(R.id.goalList);
recyclerView.setHasFixedSize(true);
adapter = new RVAdapter(getApplicationContext(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
}
public RVData mSetRecyclerGoalTitle(View view) {
editGoalTitle = (EditText) findViewById(R.id.edit_goalTitle);
editGoalTitle.setText(R.string.dummyTxt);
stringGoalTitle = editGoalTitle.getText().toString();
public List<RVData> getData () {
List<RVData> data = new ArrayList<>();
String[] titles = {};
if (stringGoalTitle != null) {
titles = new String[]{stringGoalTitle};
} else {
titles = new String[]{"DummyText1"};
}
for (int i = 0; i <= titles.length; i++) {
RVData current = new RVData();
current.goalTitle = titles[i];
data.add(current);
}
return data;
}
}
public void newGoal(View view) {
Intent intent = new Intent(MainActivity.this, NewGoal.class);
startActivity(intent);
}
#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);
}
}
RVData.java:
import android.widget.CheckBox;
public class RVData {
CheckBox checkBox;
String goalTitle;
}
RVAdapter.java:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.myViewHolder> {
List<RVData> data = Collections.emptyList();
private LayoutInflater inflater;
public RVAdapter(Context context, List<RVData> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = inflater.inflate(R.layout.goal_row, viewGroup, false);
myViewHolder holder = new myViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(myViewHolder viewHolder, int position) {
RVData current = data.get(position);
viewHolder.title.setText(current.goalTitle);
}
#Override
public int getItemCount() {
return data.size();
}
class myViewHolder extends RecyclerView.ViewHolder {
//#Bind(R.id.goalRowTitle)
TextView title;
//#Bind(R.id.goalRowCB)
CheckBox checkBox;
public myViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.goalRowTitle);
checkBox = (CheckBox) itemView.findViewById(R.id.goalRowCB);
}
}
}
activity_main.xml:
<RelativeLayout 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"
style="#style/DefaultLayoutStyle"
tools:context=".MainActivity">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
style="#style/FABStyle"
android:onClick="newGoal"
android:src="#drawable/ic_add"
app:borderWidth="0dp" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/app_bar">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/goalList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.kellarapps.zeal.NavigationDrawerFragment"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
activity_new_goal.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="#style/DefaultLayoutStyle"
tools:context="com.kellarapps.zeal.NewGoal">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<LinearLayout
android:id="#+id/goalTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/app_bar"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingEnd="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingStart="5dp">
<TextView
style="#style/DefaultTVStyle"
android:text="#string/goal" />
<EditText
android:id="#+id/edit_goalTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/goalHint" />
</LinearLayout>
<LinearLayout
android:id="#+id/goalDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/goalTitle"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingEnd="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingStart="5dp">
<TextView
style="#style/DefaultTVStyle"
android:text="#string/goalDescription" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/description"
android:maxLines="3" />
</LinearLayout>
<android.support.design.widget.FloatingActionButton
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/fab2"
style="#style/FABStyle"
android:onClick="mSetRecyclerGoalTitle"
android:src="#drawable/ic_action_done"
app:borderWidth="0dp"/>
NewGoal.java:
public class NewGoal extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_goal);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#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_new_goal, 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;
}
if(id == android.R.id.home)
{
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
}
goal_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingStart="10dp">
<CheckBox
android:id="#+id/goalRowCB"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/goalRowTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:gravity="center_horizontal"
android:text="#string/dummyTxt"
android:textColor="#color/TextColor"
android:textSize="17sp" />
From what I see, what you're trying to do is to return some info from the NewGoal activity to the MainActivity. You cannot access to the layout of other activity to recover the content of its views.
That's usually done using startActivityForResult.
Take a look at the developers reference:
http://developer.android.com/training/basics/intents/result.html
Change
public RVData mSetRecyclerGoalTitle(View view) {
editGoalTitle = (EditText) findViewById(R.id.edit_goalTitle);
editGoalTitle.setText(R.string.dummyTxt);
stringGoalTitle = editGoalTitle.getText().toString();
public List<RVData> getData () {
List<RVData> data = new ArrayList<>();
String[] titles = {};
if (stringGoalTitle != null) {
titles = new String[]{stringGoalTitle};
} else {
titles = new String[]{"DummyText1"};
}
for (int i = 0; i <= titles.length; i++) {
RVData current = new RVData();
current.goalTitle = titles[i];
data.add(current);
}
return data;
}
}
to
public void mSetRecyclerGoalTitle(View view) {
editGoalTitle = (EditText) findViewById(R.id.edit_goalTitle);
editGoalTitle.setText(R.string.dummyTxt);
stringGoalTitle = editGoalTitle.getText().toString();
}
public List<RVData> getData () {
mSetRecyclerGoalTitle(null);
List<RVData> data = new ArrayList<>();
String[] titles = {};
if (stringGoalTitle != null) {
titles = new String[]{stringGoalTitle};
} else {
titles = new String[]{"DummyText1"};
}
for (int i = 0; i <= titles.length; i++) {
RVData current = new RVData();
current.goalTitle = titles[i];
data.add(current);
}
return data;
}
There are many things going wrong with your code.
Firstly, this method does not make any sense:
public RVData mSetRecyclerGoalTitle(View view) {
editGoalTitle = (EditText) findViewById(R.id.edit_goalTitle);
editGoalTitle.setText(R.string.dummyTxt);
stringGoalTitle = editGoalTitle.getText().toString();
public List<RVData> getData () {
List<RVData> data = new ArrayList<>();
String[] titles = {};
if (stringGoalTitle != null) {
titles = new String[]{stringGoalTitle};
} else {
titles = new String[]{"DummyText1"};
}
for (int i = 0; i <= titles.length; i++) {
RVData current = new RVData();
current.goalTitle = titles[i];
data.add(current);
}
return data;
}
}
It's wrong from the first line. edit_goalTitle is not from activity_main so you will not find that View.
Next you wrote a method definition inside a method? No that's not gonna happen. That's why the IDE gives you an error.
Then you declared the onClick in xml:
android:onClick="mSetRecyclerGoalTitle"
However, this onClick thing will fail as well, because MainActivity inflated other xml file, not activity_new_goal.xml. This will only work if you put the mSetRecyclerGoalTitle method inside the activity that inflates activity_new_goal.xml.
You have a space between getData and the brackets () in your definition of the method:
public List<RVData> getData () {
...
}
Change to:
public List<RVData> getData() { // <-- deleted space
...
}

Bring up keyboard when clicking on EditText

As the title says, I want to bring up the keyboard when I click/tap on the EditText. I've looked at other questions asking for the same thing but the answers just aren't working for me. I don't think the other questions are trying to do this in the onCreate() method and I don't think that they're using this answer for not focusing on the EditText when the app begins. I've added a list of code segments of what I tried and didn't work to avoid redundant answers.
MainActivity.java:
public class MainActivity extends ActionBarActivity {
private boolean mIsPlaying;
private int primesLE;
private GridView mGridView;
private ImageAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIsPlaying = false;
ViewGroup.LayoutParams layoutParams;
primesLE = 0;
int numOfColumns = (int)Math.round(Math.sqrt((double) primesLE));
int numOfRows = (int)Math.ceil((double)primesLE/(double)numOfColumns);
View relativeLayout = findViewById(R.id.relativeLayout);
View title_horizontalScrollView = relativeLayout.findViewById(R.id.title_horizontalScrollView);
View dataLayout = title_horizontalScrollView.findViewById(R.id.dataLayout);
mGridView = (GridView) dataLayout.findViewById(R.id.mGridView);
layoutParams = mGridView.getLayoutParams();
layoutParams.width = 150*numOfColumns; //this is in pixels
mGridView.setLayoutParams(layoutParams);
mGridView.setNumColumns(numOfColumns);
mAdapter = new ImageAdapter(this, android.R.layout.simple_list_item_1, primesLE);
mGridView.setAdapter(mAdapter);
View inputLayout = relativeLayout.findViewById(R.id.inputLayout);
EditText inputEditText = (EditText)inputLayout.findViewById(R.id.inputEditText);
//list of what doesn't work
/*
inputEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
*/
/*
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(inputEditText, InputMethodManager.SHOW_IMPLICIT);
*/
/*
inputEditText.setFocusableInTouchMode(true);
inputEditText.setFocusable(true);
InputMethodManager imm = (InputMethodManager) MainActivity.this.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputEditText.getWindowToken(), 0);
inputEditText.requestFocus();
imm.showSoftInput(inputEditText, 0);
*/
/*
inputEditText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
inputEditText.getWindowToken(), 0);
return true;
}
});
*/
}
#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;
}
private void playSoE(){
for(int i = 0; i < primesLE; i++){
mAdapter.setPositionColor(i, 0xffff0000 + 0x100 * i);
}
}
#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);
}
}
activity_main.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:id="#+id/relativeLayout"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/inputLayout"
android:layout_alignParentTop="true"
android:background="#a9a9a9"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:id="#+id/textView"
android:text="All primes lower this number:"
/>
<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
android:focusable="true" android:focusableInTouchMode="true"
android:layout_width="0px" android:layout_height="0px"/>
<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="#+id/autotext"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:nextFocusUp="#id/autotext" android:nextFocusLeft="#id/autotext"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/inputEditText"
android:layout_weight="1" />
</LinearLayout>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/inputLayout"
android:id="#+id/title_horizontalScrollView"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/dataLayout"
>
<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"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</HorizontalScrollView>
</RelativeLayout>
ImageAdapter.java:
public class ImageAdapter extends ArrayAdapter {
private Context mContext;
private int mCount;
private boolean setBlueBackground = false;
private int[] gridColors;
public ImageAdapter(Context c, int resource, int count) {
super(c, resource);
mContext = c;
mCount = count;
gridColors = new int[mCount];
Arrays.fill(gridColors,Color.LTGRAY);
}
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);
textView.setGravity(Gravity.CENTER);
textView.setLayoutParams(new GridView.LayoutParams(100, 100));
} else {
textView = (TextView) convertView;
}
textView.setBackgroundColor(gridColors[position]);
textView.setText("" + position);
return textView;
}
public void setPositionColor(int position, int color) {
gridColors[position] = color;
notifyDataSetChanged();
}
}
menu_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_status"
android:icon="#drawable/ic_action_play"
android:title="Play"
app:showAsAction="always"/>
<item android:id="#+id/action_stop"
android:icon="#drawable/ic_action_stop"
android:title="Stop"
app:showAsAction="always"/>
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
P.S. I'm trying to bring up the keyboard with numbers only, and figure out how how to close it and execute it too.
You are not seeing the inputEditText because the AutoCompleteTextView control is
overlapping it. Try putting the inputEditText before the autotext and you will see the keyboard with numbers only. I also added android:orientation="vertical" to your XML.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/inputLayout"
android:layout_alignParentTop="true"
android:background="#a9a9a9"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:id="#+id/textView"
android:text="All primes lower this number:"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/inputEditText"/>
<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
android:focusable="true" android:focusableInTouchMode="true"
android:layout_width="0px" android:layout_height="0px"/>
<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="#+id/autotext"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:nextFocusUp="#id/autotext" android:nextFocusLeft="#id/autotext"/>
</LinearLayout>

Custom adapter for listview using pasrequery

I am trying to create a demo app where the users enter a search and destination, the data will be queried from parse.com and then the matching result will be displayed in the next screen's listview. I have followed a few tutorials but for sure haven't been able to grasp the concept concretely enough. When I enter a search query, the progress bar shows up and then the application goes back into the previous activity. I can't understand where exactly things are going wrong.
This is my mainactivity class.
public class CarpoolingActivitySearch extends ActionBarActivity {
ListView listView;
ArrayList<Travellers> travellers;
CarpoolingAdapter adapter;
protected ProgressDialog proDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_carpooling_activity_search);
final EditText mSrc = (EditText)findViewById(R.id.carpooling_source);
final EditText mDst = (EditText)findViewById(R.id.destination);
Button mSubmitButton = (Button)findViewById(R.id.carpooling_submit);
mSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String source = mSrc.getEditableText().toString();
String destination = mDst.getEditableText().toString();
listView = (ListView) findViewById(R.id.list);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Carpooling");
query.whereEqualTo("Source", source); //assume you have a DonAcc column in your Country table
query.whereEqualTo("Destination", destination); //assume you have a DonAcc column in your Country table
startLoading();
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if(e==null)
{
for(int i=0;i<parseObjects.size();i++)
{
Travellers travellers1 = new Travellers();
travellers1.setSource("Source");
travellers1.setDestination("Destination");
travellers.add(travellers1);
if(travellers.size() > 0)
{
adapter = new CarpoolingAdapter(getApplicationContext(),R.layout.activity_carpooling_activity_search,travellers);
listView.setAdapter(adapter);
} else {
AlertDialog.Builder popup = new AlertDialog.Builder(CarpoolingActivitySearch.this);
popup.setMessage("Seems our servers are busy. Try again in some time.");
popup.setPositiveButton("Back",null);
AlertDialog dialog = popup.create();
dialog.show();
}
}
stopLoading();
finish();
}
else {
stopLoading();
AlertDialog.Builder popup = new AlertDialog.Builder(CarpoolingActivitySearch.this);
popup.setMessage(e.getMessage());
popup.setPositiveButton("Back",null);
AlertDialog dialog = popup.create();
dialog.show();
}
}
});
}
});
}
#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_carpooling_activity_search, 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);
}
protected void startLoading() {
proDialog = new ProgressDialog(this);
proDialog.setMessage("loading...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
proDialog.setCancelable(false);
proDialog.show();
}
protected void stopLoading() {
proDialog.dismiss();
proDialog = null;
}
}
I have created a custom adapter for this purpose.
public class CarpoolingAdapter extends ArrayAdapter<Travellers> {
ArrayList<Travellers> travellersArrayList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
Context context;
public CarpoolingAdapter(Context context, int resource, ArrayList<Travellers> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
travellersArrayList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null) {
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.mSource = (TextView)convertView.findViewById(R.id.textView);
holder.mDestination = (TextView)convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.mSource.setText(travellersArrayList.get(position).getSource());
holder.mDestination.setText(travellersArrayList.get(position).getDestination());
return convertView;
}
static class ViewHolder {
public TextView mSource;
public TextView mDestination;
}
}
And the travellers class with a default constructor and getter/setter methods.
public class Travellers {
private String Source;
private String Destination;
public Travellers() {
}
public Travellers(String source, String destination) {
super();
Source = source;
Destination = destination;
}
public String getSource() {
return Source;
}
public void setSource(String source) {
Source = source;
}
public String getDestination() {
return Destination;
}
public void setDestination(String destination) {
Destination = destination;
}
}
The main layout file named activity_carpooling_activity_search.xml.
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.android.myapplication.Carpooling.Carpooling">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/carpooling_source"
android:hint="Source"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/destination"
android:hint="Destination"
android:layout_below="#+id/carpooling_source"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="86dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/carpooling_submit"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
android:layout_toEndOf="#+id/carpooling_submit"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_below="#+id/carpooling_submit">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list" />
</ScrollView>
</RelativeLayout>
And finally my list_item_deatil.xml file.
<?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"
android:weightSum="1">
<TextView
android:layout_width="174dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_weight="0.13" />
<TextView
android:layout_width="245dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2"
android:layout_weight="0.13" />
</LinearLayout>
What should I modify to make it work appropriately? I am not getting any errors as such.
First of all, you have posted a very long code blocks where indentation is not good enough to read you code.
So what I understood, as your ParseException e is null that means there is no exception. Inside that if block, after the for loop you are calling finish() which is causing your current activity instance to be destroyed thus going to previous activity.
I hope this helps you.

How do I use the swipe gesture to remove cards within a recycleview?

How do I use the swipe gesture to remove cards from my recycle-view in the same way that it is done in Google-now etc. So far I've created the cardview application but it's removing cards via a swipe gesture which I'm having problems with. I haven't found a single tutorial or question answered on this website which could help.
Any help would be very much appreciated. My code is below.
MyActivity
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_my);
setContentView(R.layout.activity_my);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
ContactAdapter ca = new ContactAdapter(createList(30));
recList.setAdapter(ca);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private List<ContactInfo> createList(int size) {
List<ContactInfo> result = new ArrayList<ContactInfo>();
for (int i=1; i <= size; i++) {
ContactInfo ci = new ContactInfo();
ci.name = ContactInfo.NAME_PREFIX + i;
ci.surname = ContactInfo.SURNAME_PREFIX + i;
ci.email = ContactInfo.EMAIL_PREFIX + i + "#test.com";
result.add(ci);
}
return result;
}
}
ContactInfo.java
public class ContactInfo {
protected String name;
protected String surname;
protected String email;
protected static final String NAME_PREFIX = "Name_";
protected static final String SURNAME_PREFIX = "Surname_";
protected static final String EMAIL_PREFIX = "email_";
}
ContactAdapter.java
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<ContactInfo> contactList;
public ContactAdapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vSurname.setText(ci.surname);
contactViewHolder.vEmail.setText(ci.email);
contactViewHolder.vTitle.setText(ci.name + " " + ci.surname);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vSurname;
protected TextView vEmail;
protected TextView vTitle;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vSurname = (TextView) v.findViewById(R.id.txtSurname);
vEmail = (TextView) v.findViewById(R.id.txtEmail);
vTitle = (TextView) v.findViewById(R.id.title);
}
}
}
activity_my.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MyActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
card_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#color/bkg_card"
android:text="contact det"
android:gravity="center_vertical"
android:textColor="#android:color/white"
android:textSize="14dp"/>
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/title"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="#+id/txtSurname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Surname"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtName"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
/>
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:layout_alignBaseline="#id/txtName"/>
<TextView
android:id="#+id/txtAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textSize="10dp"
android:layout_alignStart="#id/txtEmail"
android:layout_alignBaseline="#id/txtSurname"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
You can use below code (ItemTouchHelper.SimpleCallback from Android support V7) to remove the cards from RecyclerView using swipe gesture
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
contacts.remove(viewHolder.getAdapterPosition());
ca.notifyItemRemoved(viewHolder.getAdapterPosition());
}
#Override
public void onMoved(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int fromPos, RecyclerView.ViewHolder target, int toPos, int x, int y) {
super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recList);

Listview w/ custom adapter not loading title array only 0's with Navigation Drawer

Im looking for someone that can help me with my Navigation Drawer with a customer list adapter. Im having a issue with my Listview not populating the String arrays and my list header strings and instead loading some sort of resource id number.
Im new to listviews and just need someone that is more familiar to look over the below code to help me figure out why this is happening.
Thanks
Code
NsMenuAdapter
public class NsMenuAdapter extends ArrayAdapter<NsMenuItemModel> {
/*
* public NsMenuAdapter(Context context, int resource, int
* textViewResourceId, String[] objects) { super(context,
* R.layout.ns_menu_row, textViewResourceId, objects); }
*/
public NsMenuAdapter(Context context) {
super(context, 0);
}
public void addHeader(int title) {
add(new NsMenuItemModel(title, -1, true));
}
public void addItem(int title, int icon) {
add(new NsMenuItemModel(title, icon, false));
}
public void addItem(NsMenuItemModel itemModel) {
add(itemModel);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).isHeader ? 0 : 1;
}
#Override
public boolean isEnabled(int position) {
return !getItem(position).isHeader;
}
public static class ViewHolder {
public final TextView textHolder;
public final ImageView imageHolder;
public ViewHolder(TextView text1, ImageView image1) {
this.textHolder = text1;
this.imageHolder = image1;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
NsMenuItemModel item = getItem(position);
ViewHolder holder = null;
View view = convertView;
if (view == null) {
int layout = R.layout.ns_menu_row;
if (item.isHeader)
layout = R.layout.ns_menu_row_header;
view = LayoutInflater.from(getContext()).inflate(layout, null);
TextView text1 = (TextView) view.findViewById(R.id.menurow_title);
ImageView image1 = (ImageView) view.findViewById(R.id.menurow_icon);
view.setTag(new ViewHolder(text1, image1));
}
if (holder == null && view != null) {
Object tag = view.getTag();
if (tag instanceof ViewHolder) {
holder = (ViewHolder) tag;
}
}
if(item != null && holder != null)
{
if (holder.textHolder != null)
//holder.textHolder.setText(item.title);
holder.textHolder.setText(String.valueOf(item.title));
if (holder.imageHolder != null) {
if (item.iconRes > 0) {
holder.imageHolder.setVisibility(View.VISIBLE);
holder.imageHolder.setImageResource(item.iconRes);
} else {
holder.imageHolder.setVisibility(View.GONE);
}
}
}
return view;
}
}
NsMenuItemModel
public class NsMenuItemModel {
public int title;
public int iconRes;
public boolean isHeader;
public NsMenuItemModel(int title, int iconRes,boolean header) {
this.title = title;
this.iconRes = iconRes;
this.isHeader=header;
}
public NsMenuItemModel(int title, int iconRes) {
this(title,iconRes,false);
}
}
MainActivity
private ListView mDrawerList;
private DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
mTitle = mDrawerTitle = getTitle();
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
}
private void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
mAdapter.addHeader(R.string.header1);
menuItems = getResources().getStringArray(
R.array.dashboard_array);
String[] menuItemsIcon = getResources().getStringArray(
R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
mAdapter.addItem(mItem);
res++;
}
mAdapter.addHeader(R.string.header2);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
super(
mActivity,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.solartools_gosolar_title));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.solartools_pvwatts_title));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mDrawerList.setItemChecked(position, true);
String text= "menu click... should be implemented";
Toast.makeText(MainActivity.this, text , Toast.LENGTH_LONG).show();
mDrawer.closeDrawer(mDrawerList);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
Layouts
**ms_menu_row_header**
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="center_vertical" >
<TextView
android:id="#+id/menurow_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:padding="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:singleLine="true"
android:text=""
android:textAllCaps="true"
android:textAppearance="#android:style/TextAppearance.Medium"
android:textStyle="bold" />
<ImageView
android:id="#+id/menu_divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/menurow_title"
android:src="#DADADC" />
</RelativeLayout>
**ns_menu_row**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ns_menu_row"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/menurow_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/menurow_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:background="#DADADC" />
</LinearLayout>
**activity_dashboard**
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/left_drawer"
style="#style/ListViewAppTheme"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffff"
android:choiceMode="singleChoice"
android:divider="#cecbce"
android:dividerHeight="1dp"
android:dividerPadding="1dp" />
</android.support.v4.widget.DrawerLayout>
Array
<string-array name="dashboard_array">
<item>Home</item>
<item>Community</item>
<item>Blog</item>
<item>Website</item>
<item>The latest</item>
<item>News</item>
<item>Support</item>
</string-array>
<array name="ns_menu_items_icon">
<item>ic_action_web_site</item>
<item>ic_action_share</item>
<item>ic_action_negative</item>
<item>ic_action_web_site</item>
<item>ic_action_new</item>
<item>ic_action_negative</item>
<item>ic_action_expand</item>
</array>
and instead loading some sort of resource id number.
What you see is what you should get based on your code. First of all, for the big number(21... which is a string id from your code), you get this because in your getView() method you use:
holder.textHolder.setText(String.valueOf(item.title));
item.title is the id of the string resource and you can't just pas it around expecting to get the actual string, you need to convert it before using. This could be done using:
holder.textHolder.setText(getContext().getResources().getString(item.title));
For the rows with the 0 text, that's happening because you don't setup the non header rows properly. You have the strings in an string array resource, dashboard_array, but when you build the adapter's items you use a for loop with:
int id_title = getResources().getIdentifier(item, "string", this.getPackageName());
This will not work because you're looking for a string resource by a name that only exists in a string array resource(so there's no R.string.item_name_here) which will return 0, which you later insert as the text like you did for the header. So you either break that string array resources in 7 individual strings and use your current code(with the getIdentifier() method) or you change the way you handle the text for non header rows(to not use item.title for normal rows).
As a side note, you're not properly implementing the two types of rows for the ListView. The idea is to implement the getViewTypeCOunt and getItempViewType() methods and then use them in the getView() method to inflate and set the proper row type. There're a lot of example out there on how to do this.

Categories