I've been searching for hours and hours on trying to understand the relationship between Fragments and Activities and I still cant get it right with my code.
I have a mainScreen class that loads actvity_main.xml. This main screen has a layout with a graph and sidebar etc.
I have a button that is on the side bar that is supposed to launch a sidebar fragment that has a checkbox listview in it so I can select data to show on my graph etc. But that fragment is not showing no matter what I do. It shows the "Bing~!" Toast but no other view is launched.
Perhaps I shouldn't be using a fragment? I don't want to start a new activity as the checkbox is supposed to interact with the graph and another fragment with a dynamic table in it and it will interact back and forth and so on.
I'm not too sure what to do here. I have about 3 weeks of Android experience so I'm not exactly knowledgeable about the whole shebang of it just yet. Really appreciate any ideas or help I can get. I am completely stumped and hence had to post my own question.
I really really appreciate any kind of help! Thanks!
mainScreen.java
public class mainScreen extends Activity {
private TextView text_display;
private Button button_list;
private Button button_table;
private String[] dataHolder;
public boolean listClicked = false;
public void loadData () {
//loaddata stuff here
}
public void createGraph () {
//graph create stuff here
}
public void buttonClick () {
button_list.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
sideFragment sf = new sideFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.side_fragment, sf);
ft.commit();
Toast.makeText(mainScreen.this, "Bing~!", Toast.LENGTH_SHORT).show();
}
}
);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = getIntent();
dataHolder = i.getStringArrayExtra("dataHolder");
button_list = (Button)findViewById(R.id.button_list);
loadData();
createGraph();
buttonClick();
}
}
activity_main.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"
tools:context=".mainScreen"
android:id="#+id/mainlayout"
android:orientation="horizontal"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="85dp"
android:layout_height="match_parent">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="85dp"
android:layout_height="85dp"
android:text="Select"
android:id="#+id/button_list" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="85dp"
android:layout_height="85dp"
android:text="Table"
android:id="#+id/button_table" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:text=" "
android:id="#+id/text_display"
android:textSize="26dp"
android:layout_margin="5dp" />
<com.jjoe64.graphview.GraphView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/graph" />
</LinearLayout>
<fragment
android:name="xabre.mobileicip.sideFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/side_fragment" />
</LinearLayout>
sideFragment.java
public class sideFragment extends Fragment implements android.widget.CompoundButton.OnCheckedChangeListener {
ListView listviewFrag;
ArrayList<sideFrag> sideFragList;
sideFragAdapter sfAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.side_fragment, container, false);
listviewFrag = (ListView) view.findViewById(R.id.side_listview);
//displayList();
return view;
}
private void displayList() {
sideFragList = new ArrayList<sideFrag>();
sideFragList.add(new sideFrag("SPO2"));
sideFragList.add(new sideFrag("O2 Flow Rate"));
sideFragList.add(new sideFrag("Resp."));
sideFragList.add(new sideFrag("Cardiac Output"));
sideFragList.add(new sideFrag("Cardiac Index"));
sideFragList.add(new sideFrag("SVR"));
sideFragList.add(new sideFrag("Wedge Pressure"));
listviewFrag.setAdapter(sfAdapter);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = listviewFrag.getPositionForView(buttonView);
if (pos != ListView.INVALID_POSITION) {
sideFrag sf = sideFragList.get(pos);
sf.setSelected(isChecked);
Toast.makeText(getActivity(),"" + sf.getName(), Toast.LENGTH_SHORT).show();
//Toast.makeText(sideFragment.this, "Clicked on sideFrag: " + sf.getName() + ". State: is " + isChecked, Toast.LENGTH_SHORT).show();
}
}
}
side_fragment.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".sideFragment"
android:id="#id/side_fragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="HELLO WORLD"
android:id="#+id/helloTester"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp">
<ListView
android:id="#+id/side_listview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
</LinearLayout>
side_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<CheckBox android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onCheckboxClicked"
android:layout_marginBottom="15dp" />
<TextView
android:id="#+id/check_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/check_box"
android:textStyle="bold"/>
</RelativeLayout>
sideFragAdapter.java
package xabre.mobileicip;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.List;
class sideFrag {
String name;
boolean selected = false;
public sideFrag(String name) {
super();
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class sideFragAdapter extends ArrayAdapter<sideFrag> implements CompoundButton.OnCheckedChangeListener {
private List<sideFrag> sideList;
private Context context;
public sideFragAdapter (List<sideFrag> sideList, Context context) {
super(context, R.layout.side_list, sideList);
this.sideList = sideList;
this.context = context;
}
private static class sideHolder {
public CheckBox check_box;
public TextView check_name;
/* public CheckBox check_O2FR;
public CheckBox check_Resp;
public CheckBox check_Carout;
public CheckBox check_Carind;
public CheckBox check_svr;
public CheckBox check_resprate;
public CheckBox check_Peep;
public CheckBox check_O2AF;
public CheckBox check_FIO2;
public CheckBox check_PO2;
public CheckBox check_HCO3;
public CheckBox check_Urea;
public CheckBox check_Potassium;
public CheckBox check_Sodium;
public CheckBox check_Creatinine;
public CheckBox check_FluidIn;
public CheckBox check_FluidOut;
*/
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
sideHolder holder = new sideHolder();
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.side_list, parent, false);
holder.check_box = (CheckBox) v.findViewById(R.id.checkbox);
holder.check_name = (TextView) v.findViewById(R.id.check_name);
holder.check_box.setOnCheckedChangeListener(this);
} else {
holder = (sideHolder) v.getTag();
}
sideFrag p = sideList.get(position);
holder.check_name.setText(p.getName());
holder.check_box.setChecked(p.isSelected());
holder.check_box.setTag(p);
return v;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
}
}
You can only replace elements added from code. side_fragment is added in XML and as such is part of, let's say "read only" structure. You need to remove <fragment> element it from XML, and add it from code if you want to replace it later.
Related
I am currently facing difficulty trying to group the switches inside recylerView. I have attached my code below and a snapshot of the screen.
As you can see, I can now toogle any switch but at a given point in time , I want only one switch to be toggled on.
Item_list.xml :-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:paddingBottom="#dimen/row_padding_vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/row_padding_vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="87dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="5dp"
android:layout_marginRight="30dp"
card_view:cardCornerRadius="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="95dp"
android:background="#20b2aa"
android:orientation="vertical">
<LinearLayout
android:layout_width="182dp"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
android:layout_marginRight="30dp"
android:orientation="horizontal">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffff"
android:textSize="32dp" />
</LinearLayout>
<Switch
android:id="#+id/value"
android:layout_width="59dp"
android:layout_height="3dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="-35dp"
android:layout_marginBottom="100dp"
android:scaleX="1.1"
android:scaleY="1.1"
android:theme="#style/SwitchTheme" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</RelativeLayout>
ItemAdapter:-
package com.example.loginpage;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import java.util.List;
public class ItemAdapter extends
RecyclerView.Adapter<ItemAdapter.MyViewHolder> {
private int cn=0;
private List<Item> itemList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public Switch value;
public MyViewHolder(View view) {
super(view)
name = (TextView) view.findViewById(R.id.name);
value = (Switch) view.findViewById(R.id.value);
}
}
public ItemAdapter(List<Item> itemList) {
this.itemList = itemList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Item item = itemList.get(position);
holder.name.setText(item.getName());
}
#Override
public int getItemCount() {
return itemList.size();
}
}
My current interface looks like this....
https://www.pastepic.xyz/image/8z5Eh
I suggest that you set a Click listener on all value switches and disable all switches when any switch clicked.
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Item item = itemList.get(position);
holder.name.setText(item.getName());
holder.value.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (Item x: itemList){
// x.Selected=false;
// here you make all of your switches to false
}
//itm.Selected = true;
// here you make the current switch to on or true
notifyDataSetChanged();
}
});
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Item item = itemList.get(position);
holder.name.setText(item.getName());
holder.value.setChecked(item.isValueChecked());
holder.value.setOnCheckedChangeListener(new OnCheckedChangeListener(
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
for(Item i: itemList){
i.setValueChecked(false);
}
if(buttonView.isChecked()){
itemList.get(position).setValueChecked(true);
holder.value.setChecked(true);
}
notifyDataSetChanged();
}
});
}
Try this solution, this should work...
Checked Change Listener is set on the switch if any switch is turned ON then all the values of the itemList is made false and current value is made True and switch is set ON, finally, notifyDataSetChanged() is called.
If any switch is turned OFF then all the values in the itemList are made False and notifyDataSetChanged() is called so that the switch state gets updated.
holder.value.setChecked(item.isValueChecked());
This updates the switch state based on the values stored in the itemList.
I'm developing an English-Japanese learning app, where it has a stack of cards where users can swipe through, and on each current card, the user can touch the card to flip to the other side of a card, which show the meaning of the word.
For the swipe function, I'm using a library SwipeFlingAdapterView, which support setOnItemClick. Now I need to do the flipping part. I read the tutorial here, which requires 2 fragments to do the flip:
https://developer.android.com/training/animation/cardflip.html
The structure Im setting below:
stack_of_cards_fragment.xml
<FrameLayout 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"
......
>
<com.lorentzos.flingswipe.SwipeFlingAdapterView
android:id="#+id/swipeFlingAdapterViewFront"
android:layout_width="match_parent"
android:layout_height="match_parent"
</com.lorentzos.flingswipe.SwipeFlingAdapterView>
</FrameLayout>
StackOfCardsFragment.java
public class StackOfCardsFragment extends Fragment {
ArrayList<TestModel> cardsList;
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.stack_of_cards_fragment,container,false);
final CardsAdapter arrayCardsAdapter;
cardsList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
//dump data
TestModel model = new TestModel();
model.isFlipped = false;
cardsList.add(model);
}
SwipeFlingAdapterView flingContainer = ButterKnife.findById(view,R.id.swipeFlingAdapterViewFront);
ButterKnife.bind(this, view);
arrayCardsAdapter = new CardsAdapter(context, cardsList);
flingContainer.setAdapter(arrayCardsAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
Log.d("LIST", "removed object!");
if(!cardsList.isEmpty())
{arrayCardsAdapter.remove(0);}
}
#Override
public void onLeftCardExit(Object dataObject) {
Log.e("Swipe Direction","Left");
}
#Override
public void onRightCardExit(Object dataObject) {
Log.e("Swipe Direction","Right");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
if(!cardsList.isEmpty()) {
arrayCardsAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
}else Log.e("Check Empty","Its empty");
}
#Override
public void onScroll(float scrollProgressPercent) {
Log.e("onScroll", "scrollProgressPercent");
}
});
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
//This is where I want to change the Front Card Fragment to Back Card Fragment.
}
});
return view;
}
}
and below is the part where I'm struggling to do.
flash_card_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/holo_blue_dark">
<LinearLayout
android:id="#+id/child_fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
CardsAdapter.java
public class CardsAdapter extends BaseAdapter {
Context context;
ArrayList<TestModel> cardsList;
ViewFlipper viewFlipper;
public CardsAdapter(Context context, ArrayList cardsList ) {
this.context = context;
this.cardsList = cardsList;
}
#Override
public int getCount() {
return cardsList.size();
}
#Override
public Object getItem(final int i) {
return cardsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, final ViewGroup viewGroup) {
if (view == null) {
LayoutInflater vi = (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.flash_card_layout, viewGroup, false);
//This is where I want to set the Front Card Fragment
Fragment frontCardFragment = new EachFrontCardFragment();
FragmentTransaction transaction = ((VocabularyGameActivity) context).getSupportFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.add(R.id.child_fragment_container, frontCardFragment);
transaction.commit();
}
return view;
}
public void remove(int i) {
cardsList.remove(i);
notifyDataSetChanged();
}
}
each_card_front_fragment.xml and one for the each_card_back_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cardviewfront">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp">
<TextView android:id="#+id/txtWord_cardfront"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="English"
android:textStyle="bold"
android:textSize="50sp"
android:textColor="#android:color/black"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:layout_marginBottom="50dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
I already created 2 fragments for each_card_front_fragment and each_card_back_fragment.
What am I missing here? All the code above is only showing me the cardAdapter in the StackOfCardsFragment(which is only a background), but the each_card_front_fragment doesn't show up.
I already try set up a BroadcastReceiver from (CardsAdapter)BaseAdapter to send to the VocabulartyActivity to set the each_card_front_fragment there but the same outcome.
is the any other way to set the Fragment in the BaseAdapter?
I am writing a ListView with 2 TextViews per row, but when I execute I get only one TextView.
Here is my adapter extending Base adapter
public class GlossaryListViewAdapter extends BaseAdapter {
List<Glossary_Entry> glossary_entryList;
Context context;
public GlossaryListViewAdapter(Context context,List<Glossary_Entry> glossary_entryList){
this.glossary_entryList = glossary_entryList;
this.context = context;
}
#Override
public int getCount() {
return glossary_entryList.size();
}
#Override
public Object getItem(int postion) {
return glossary_entryList.get(postion);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null){
view = LayoutInflater.from(context).inflate(R.layout.glossary_single_row,viewGroup,false);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder)view.getTag();
}
viewHolder.titleTextView.setText(glossary_entryList.get(position).getTitle());
viewHolder.definitionTextView.setText(glossary_entryList.get(position).getDefinition());
return view;
}
private static class ViewHolder{
TextView titleTextView;
TextView definitionTextView;
public ViewHolder(View view){
titleTextView = (TextView)view.findViewById(R.id.glossary_title_textview);
definitionTextView = (TextView)view.findViewById(R.id.glossary_word_definition_textview);
}
}
}
Here is my Activity code
public class GlossaryAcvtivity extends AppCompatActivity {
ListView glossaryListView;
ListAdapter listAdapter;
List<Glossary_Entry> glossary_entryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glossary);
/**
* Sample data
*/
glossary_entryList = new ArrayList<>();
glossary_entryList.add( new Glossary_Entry("Force","This is a push or push on an object.They can be duew to a phenomenon such as gravity, magnetism, or anything that might cause a mass to accelerate."));
glossary_entryList.add( new Glossary_Entry("Motion","Change in position of an object over time, described in terms of displacement,distance,velocity,acceleration,time and speed"));
glossary_entryList.add( new Glossary_Entry("Quantum Leap","An Abrupt transition of an electron,atom, or molecule from one quantum state to another,with the absorption or emission of a quantum"));
glossary_entryList.add( new Glossary_Entry("Force","This is a push or push on an object.They can be duew to a phenomenon such as gravity, magnetism, or anything that might cause a mass to accelerate."));
glossaryListView = (ListView)findViewById(R.id.glossary_list_view);
listAdapter = new GlossaryListViewAdapter(getApplicationContext(),glossary_entryList);
glossaryListView.setAdapter(listAdapter);
}
}
The source of my data is an Entry class
public class Glossary_Entry {
public String title;
public String definition;
public String getTitle() {
return title;
}
public String getDefinition() {
return definition;
}
public Glossary_Entry(String title,String definition){
this.title = title;
this.definition = definition;
}
}
Here is my glossary_single_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="16sp"
android:layout_margin="4dp"
android:id="#+id/glossary_title_textview"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_description"
android:layout_margin="4dp"
android:textSize="12sp"
android:id="#+id/glossary_word_definition_textview"/>
</LinearLayout>
Here is my glossary_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#color/white"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:id="#+id/glossary_toolbar"
android:background="#color/colorPrimary"
android:layout_height="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
<ListView
android:layout_width="match_parent"
android:id="#+id/glossary_list_view"
android:layout_margin="8dp"
android:layout_below="#+id/glossary_toolbar"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
Please help when I execute I get only one TextView per row...
Apparently, I needed to change the text color to black in the second TextView. The text was there just not visible.
<LinearLayout xmlns:android="http:// schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="16sp" android:layout_margin="4dp"
android:id="#+id/glossary_title_textview"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_description"
android:layout_margin="4dp"
android:textSize="12sp"
android:textColor="#color/black"
android:id="#+id/glossary_word_definition_textview"/>
</LinearLayout
Check this image sample i have done it Material Design Gridview Image
I have done the same Material Design for grid view Activity on my app, i like to add the onItemClick to new Activity,
I don't know how to do this , please give the brief explanation for the solution
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/android_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:id="#+id/appbar_layout"
android:layout_height="#dimen/app_bar_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_android_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="#dimen/expanded_toolbar_title_margin_start"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/code"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:id="#+id/nestedscrollview"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="#+id/grid"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:gravity="center"
android:listSelector="#00000000"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
res/layout/gridview_custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/android_gridview_custom_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<com.andexert.library.RippleView
android:id="#+id/more"
rv_centered="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:rv_color="#fff"
app:rv_rippleDuration="200">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearLayout"
android:orientation="vertical">
<ImageView
android:id="#+id/gridview_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/gridview_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/grid_image"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Grid View Item"
android:textColor="#444"
android:textSize="12sp"
android:textStyle="bold" />
</LinearLayout>
</com.andexert.library.RippleView>
</LinearLayout>
src/MainActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.GridView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"Android",
"Java",
"GridView",
"ListView",
"Adapter",
"Custom GridView",
"Material",
"XML",
"Code",
};
public static int[] gridViewImages = {
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("Material Grid");
}
}
src/CustomAndroidGridViewAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by HP on 5/11/2016.
*/
public class CustomAndroidGridViewAdapter extends BaseAdapter {
private Context mContext;
private final String[] string;
private final int[] Imageid;
public CustomAndroidGridViewAdapter(Context c,String[] string,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.string = string;
}
#Override
public int getCount() {
return string.length;
}
#Override
public Object getItem(int p) {
return null;
}
#Override
public long getItemId(int p) {
return 0;
}
#Override
public View getView(int p, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.gridview_custom_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
textView.setText(string[p]);
imageView.setImageResource(Imageid[p]);
} else {
grid = (View) convertView;
}
return grid;
}
}
PLease give me the solution for call another Actvivty when mouse click on Image (Image 1, Image 2, etc) in Gridview this
Replace your method with mine
#Override
public View getView(int p, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.gridview_custom_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
textView.setText(string[p]);
imageView.setImageResource(Imageid[p]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,YourActivity.class);
context.startActivity(intent);
}
});
} else {
grid = (View) convertView;
}
return grid;
}
here is the code to go another activity after click on every image.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"Android",
"Java",
"GridView",
"ListView",
"Adapter",
"Custom GridView",
"Material",
"XML",
"Code",
};
public static int[] gridViewImages = {
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
if(gridViewStrings[position].equalsIgnoreCase(String.valueOf(1))){
Intent intent=new Intent(MainActivity.this,SecoundActivity.class);
intent.putExtra("image",gridViewImages[position]);
startActivity(intent);
}
else if(gridViewStrings[position].equalsIgnoreCase(String.valueOf(2))){
Intent intent2=new Intent(MainActivity.this,ThirdActvity.class);
intent2.putExtra("image2",gridViewImages[position]);
startActivity(intent2);
}
//Like this create activites how many images are there in gridViewImages[]array.you have 9 images so create nine activities..you have to send the url in every activity from one activity to another activity according to your requirement
}
});
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("Material Grid");
}
}
create SecoundActivity.class
public class SecoundActivity extends AppCompactActivity{
private ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
int position = intent.getExtras().getInt("image");
setContentView(R.layout.secound_view);
image=(ImageView) findViewById(R.id.image);
image.setImageResource(position);
}
}
then Finally create the secound_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_horizontal_margin">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/image"
/>
</LinearLayout>
After 10 seconds in Google...
Starting Another Activity
Intent intent = new Intent(this, YourActivity.class);
startActivity(intent);
And Click Listener/Event
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Item Clicked: " + position, Toast.LENGTH_SHORT).show();
}
});
In your MainActivity onCreate method, add an OnItemClick listener for the GridView:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Your Intent goes here
}
});
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.