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
...
}
Related
I am developing an bus time table android app. I have three fragments.
Inside first fragment I have two radio buttons i.e. From Malegaon & To Malegaon. (Malegaon is name of place).
If I select From Malegaon radio button then I am setting text to sourceEditText as Malegaon. and If I select To Malegaon radio button then I am setting text to destinationEditText as Malegaon.
This condition is working fine, when I visit fragment first time, but if I revisit fragment then From Malegaon radio Button is already selected, sourceEditText is blank and destinationEditText has text as Malegaon.
Here is my snapshot and code for first fragment.
after selecting to Malegaon radio button.
I am just changing visibility of layout. (source edittext,destination edittext,search button is one layout)
OldStandFragment.java
public class OldStandFragment extends Fragment {
public static OldStandFragment fragment ;
private static final String ARG_POSITIONS = "position";
private int positions;
private View myFragmentViewOld;
private LinearLayout fromOldMalegoanView, toOldMalegoanView;
Button selectRouteButton;
public static final String required_dest = "Please Enter Destination";
public static final String required_source = "Please Enter Source";
String language = "";
DbHelper helper;
private String sourceId = "", destinationId = "";
private ArrayList<Route> myArrayList;
private RouteAdapter routeAdapter;
private ListView routeListView;
private EditText sourceEditTextFromMalegoanOld;
private EditText destinationEditTextFromMalegoanOld;
private ImageButton searchFromMalegoanButtonOld;
private EditText sourceEditTextToMalegoanOld;
private EditText destinationEditTextToMalegoanOld;
private ImageButton searchToMalegoanButtonOld;
private RadioButton fromOldMalegoanRadioButton, toOldMalegoanRadioButton;
public OldStandFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
positions = getArguments().getInt(ARG_POSITIONS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentViewOld = inflater.inflate(R.layout.fragment_old_stand, container, false);
selectRouteButton = (Button) myFragmentViewOld.findViewById(R.id.selectRouteButton);
fromOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.fromOldMalegoanRadioButton);
toOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.toOldMalegoanRadioButton);
fromOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.fromOldMalegoanView);
toOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.toOldMalegoanView);
sourceEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.destinationEditText);
searchFromMalegoanButtonOld = (ImageButton) fromOldMalegoanView.findViewById(R.id.searchResultButton);
sourceEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.destinationEditText);
searchToMalegoanButtonOld = (ImageButton) toOldMalegoanView.findViewById(R.id.searchResultButton);
SharedPreferences prefs = getContext().getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
int a = prefs.getInt("LangValue", 0);
if (a == 0) {
language = "English";
} else {
language = "मराठी";
}
helper = new DbHelper(getContext());
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
String stopValue = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue);
fromOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (fromOldMalegoanRadioButton.isChecked()) {
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
helper = new DbHelper(getContext());
String stopValue1 = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue1);
destinationEditTextFromMalegoanOld.setText("");
}
}
});
toOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (toOldMalegoanRadioButton.isChecked()) {
fromOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.GONE);
toOldMalegoanView.setVisibility(View.VISIBLE);
helper = new DbHelper(getContext());
String stopValue2 = helper.getStopName("1", language);
destinationEditTextToMalegoanOld.setText(stopValue2);
sourceEditTextToMalegoanOld.setText("");
}
}
});
searchFromMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
searchToMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
return myFragmentViewOld;
}
public static OldStandFragment newInstance(int position) {
if(fragment == null) {
fragment = new OldStandFragment();
}
Bundle bundle = new Bundle();
bundle.putInt(ARG_POSITIONS, position);
fragment.setArguments(bundle);
return fragment;
}
}
fragment_old_stand.xml
<LinearLayout 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:orientation="vertical"
android:background="#000000"
android:scrollbars="vertical"
tools:context="com.ashishkudale.malegoanagar.Fragments.OldStandFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Direction or Route"
android:gravity="center"
android:textColor="#FFFFFF"
android:id="#+id/Note"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_margin="15dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/rg_ContainerOld"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="15dp">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="From Malegaon"
android:id="#+id/fromOldMalegoanRadioButton"
android:layout_marginLeft="5dp"
android:checked="false" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/fromOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="To Malegaon"
android:id="#+id/toOldMalegoanRadioButton"
android:layout_marginLeft="5dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/toOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
</RadioGroup>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Select Route "
android:id="#+id/selectRouteButton"
android:background="#drawable/button_effect"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
this is Adapter to call fragment.
MyPagerAdapter
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Old Stand","New Stand", "Fare"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment fragment = null;
if(position ==0) {
fragment = OldStandFragment.newInstance(position);
}else if(position ==1 ){
fragment = NewStandFragment.newInstance(position);
} else if (position == 2) {
fragment = MapFragment.newInstance(position);
}
return fragment;
}
}
after revisiting OldStandFragment it look like this.
I checked with adding logs everywhere possible. And I found that after revisiting OldStandFragment, toOldMalegoanRadioButton.setOnClickListner() method is getting called.
Now I want to refresh fragment when I re-visit or any other way to solve this issue.
You have to use SharedPreferences to save state of checkbox, try this code
public class StackOne extends AppCompatActivity {
SharedPreferences prefs;
private RadioButton rButton1, rButton2;
private RadioGroup rg_ContainerOld;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stack_one);
prefs = PreferenceManager.getDefaultSharedPreferences(StackOne.this);
rButton1 = (RadioButton) findViewById(R.id.fromOldMalegoanRadioButton);
rButton2 = (RadioButton) findViewById(R.id.toOldMalegoanRadioButton);
rg_ContainerOld = (RadioGroup) findViewById(R.id.rg_ContainerOld);
GetSelectedRadioButton();
int k = prefs.getInt("rb1", 0);
if (k == 1) {
rButton1.setChecked(true);
sourceEditTextFromMalegoanOld.setText("");
} else if (k == 2) {
rButton2.setChecked(true);
sourceEditTextToMalegoanOld.setText("");
}
}
private void GetSelectedRadioButton() {
rg_ContainerOld.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getCheckedRadioButtonId()) {
case R.id.fromOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 1).commit();
break;
case R.id.toOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 2).commit();
break;
}
}
});
}
}
In your code you are dynamically setting checked state of radiobutton
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
thats why your radiobutton's oncheckedchanged method will get call. And thats why code in it.
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
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 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);
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.