I'm trying to make a app in Android Studio where you have defined URLs in the spinner. And when you choose a item in the spinner it should load the URL into spinner.
I have gotten some help with this, but now I face another problem: I'm getting:
cannot resolve symbol method loadUrl java.lang.strin
My XML code:
<resources>
<string name="app_name">Obligatorisk1</string>
<string-array name="spinner">
<item value="http://www.vg.no">VG</item>
<item value="http://www.dagbladet.no">Dagbladet</item>
<item value="http://www.nettavisen.no">Nettavisen</item>
</string-array>
<string name="omAppen">Om Appen</string>
<string name="title_activity_main2">Om Appen</string>
My main activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener{
private Button omAppenKnapp;
Spinner spinner;
WebView wb1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
wb1 = (WebView) findViewById(R.id.webView);
wb1.getSettings().setJavaScriptEnabled(true);
ArrayAdapter adapter=ArrayAdapter.createFromResource(this,
R.array.spinner, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int i, long l) {
String urlName = adapterView.getItemAtPosition(i).toString();
String urlValue = "http://www.google.com";
switch (urlName) {
case "VG":
urlValue = "http://www.vg.no";
break;
case "Dagbladet":
urlValue = "http://www.dagbladet.no";
break;
case "Nettavisen":
urlValue = "http://www.nettavisen.no";
break;
}
view.loadUrl(urlValue);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
wb1.loadUrl("http://www.google.com");
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
and layout:
<?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: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=".MainActivity">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/webView"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/spinner" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/omAppen"
android:id="#+id/buttonOmOss"
android:onClick="visOmAppen"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Try this :
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected_url = spinner.getSelectedItem().toString();
view.loadUrl(selected_url);
}
EDIT
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private Button omAppenKnapp;
Spinner spinner;
WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner= (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter=ArrayAdapter.createFromResource(this, R.array.spinner, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new browser());
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected_url = spinner.getSelectedItem().toString();
view.loadUrl(selected_url);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
You can do something like this:
public class MainActivity extends AppCompatActivity {
Spinner spinner;
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
ArrayAdapter adapter=ArrayAdapter.createFromResource(this, R.array.spinner, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String urlName = adapterView.getItemAtPosition(i).toString();
String urlValue = "http://www.google.com";
switch (urlName)
{
case "VG":
urlValue ="http://www.vg.no";
break;
case "Dagbladet":
urlValue = "http://www.dagbladet.no";
break;
case "Nettavisen":
urlValue = "http://www.nettavisen.no";
break;
}
webView.loadUrl(urlValue);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
webView.loadUrl("http://www.google.com");
}
});
}
}
Related
I am using viewpager as parent and have three fragments as child. Inside all fragments I have 12 edittext. Now I am able to scroll vertically within fragment but when I scroll horizontally fragments doesn't changing.
activity.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
fragment.xml
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fffbfbfb"
android:padding="1dp">
............12 edittext
</scrollview>
activity.java
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
public ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
fragment.java
public class OneFragment extends Fragment {
private EditText etA, etB, etC, etD, etE, etF, etG, etH, etI, etJ, etK, etL;
private TextView tvProfit;
private ScrollView scrollView;
public OneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
etA = (EditText) view.findViewById(R.id.etboxA);
etB = (EditText) view.findViewById(R.id.etboxB);
etC = (EditText) view.findViewById(R.id.etboxC);
etD = (EditText) view.findViewById(R.id.etboxD);
etE = (EditText) view.findViewById(R.id.etboxE);
etF = (EditText) view.findViewById(R.id.etboxF);
etG = (EditText) view.findViewById(R.id.etboxG);
etH = (EditText) view.findViewById(R.id.etboxH);
etI = (EditText) view.findViewById(R.id.etboxI);
etJ = (EditText) view.findViewById(R.id.etboxJ);
etK = (EditText) view.findViewById(R.id.etboxK);
etL = (EditText) view.findViewById(R.id.etboxL);
tvProfit = (TextView) view.findViewById(R.id.tvprofit);
scrollView = (ScrollView) view.findViewById(R.id.scrollView);
scrollView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
scrollView.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume(){
super.onResume();
etB.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!etB.getText().toString().equals("")) {
float ans = (float) (Float.parseFloat(etB.getText().toString()) / 355.6164);
etC.setText(String.valueOf(ans));
} else {
etC.setText("");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
So suggest me how to switch touch events between scrollview and viewpager
Modify your code as follows Perhaps the problem is resolved.Cut and copy viewpager out of TabLayout .
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
I think you are removing ViewPager ability to handle touch event, try removing:
viewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
I am trying to dynamically change a text from a fragment textview inside de activity but I keep getting 'cannot obtain root' error. I tried to instantiate the textview inside onCreateView and inside onActivityCreated as well but it doesnt work. How can I change the text from a fragment textview inside the activity?
Fragment xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab 1"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
Fragment Code:
public class TabFragment1 extends Fragment {
private TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv = (TextView) getView().findViewById(R.id.textView);
}
public void setText(String text){
tv.setText(text);
}
}
Main xml:
<RelativeLayout
android:id="#+id/main_layout"
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
Main code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
TabFragment1 t1 = new TabFragment1();
TabFragment2 t2 = new TabFragment2();
TabFragment3 t3 = new TabFragment3();
adapter.newFrag(t1);
adapter.newFrag(t2);
adapter.newFrag(t3);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
t1.setText("HELLO WORLD");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
List<Fragment> aFrag;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
aFrag = new ArrayList<Fragment>();
}
public void newFrag(Fragment f){
aFrag.add(f);
}
#Override
public Fragment getItem(int position) {
return aFrag.get(position);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
You try to set text on view, but this view wasn't created, this fragment wasn't created. If You want to set text from activity you can pass bundle to fragment arguments with that text, and in fragment chceck bundle and set text. Later if you want to change text in this fragment then you can use your function.
public class TabFragment1 extends Fragment {
private TextView tv;
public static TabFragment1 create(String text){
Bundle b = new Bundle();
b.putString("textdata",text);
TabFragment1 f = new TabFragment1();
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
tv = (TextView) view.findViewById(R.id.textView);
if(getArguments()!=null){
tv.setText(getArguments().getString("textdata"));
}
return view;
}
public void setText(String text){
tv.setText(text);
}
}
In your activity create this fragment using static method:
TabFragment1 t1 =TabFragment1.create("HELLO WORLD");
Hardcore execution of your base code is:
new Handler().postDelayed(new Runnable(){t1.setText("HELLO WORLD");},300);
I'm working on an application that needs to have a Custom list in a fragment.
I try a lot of thing in vain... This is my best result:
MainActivity.java :
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_list);
if(findViewById(R.id.fragment_container) != null )
{
if(savedInstanceState != null)
return;
}
ListFragment listFragment = new ListFragment();
listFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, listFragment).commit();
}
}
stops.java:
public class stops {
private String name;
private String destination;
private String schedule;
private int iconID;
public stops(String name, String destination, String schedule, int iconID)
{
super();
this.name = name;
this.destination = destination;
this.schedule = schedule;
this.iconID = iconID;
}
public String getName(){ return name; }
public String getDestination(){ return destination; }
public String getSchedule(){ return schedule; }
public int getIconID(){ return iconID; }
}
ListFragment.java:
import android.content.Context;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ListFragment extends Fragment{
private List<stops> mystops = new ArrayList<>();
ArrayAdapter<stops> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
populateStopList();
View V = inflater.inflate(R.layout.fragment_list, container, false);
Context context = getActivity().getApplicationContext();
adapter = new myListAdapter(context);
ListView list = (ListView) V.findViewById(R.id.stopsList);
list.setAdapter(adapter);
return V;
}
private void populateStopList() {
mystops.add(new stops("Corum", "Odysseum", "5min", R.drawable.green_tram));
mystops.add(new stops("Corum", "Mosson", "2min", R.drawable.orange_tram));
mystops.add(new stops("Corum", "Saint-Jean de Vedas", "1min", R.drawable.red_tram));
}
private class myListAdapter extends ArrayAdapter<stops> {
public myListAdapter(Context context) {
super(context, R.layout.item_view, mystops);
add(new stops("Corum", "Mosson", "2min", R.drawable.green_tram));
populateStopList();
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null)
itemView = getActivity().getLayoutInflater().inflate(R.layout.item_view, parent, false);
stops currentStop = mystops.get(position);
ImageView imageView = (ImageView)itemView.findViewById(R.id.item_icon);
imageView.setImageResource(currentStop.getIconID());
TextView nameText = (TextView)itemView.findViewById(R.id.item_nameTextView);
nameText.setText(currentStop.getName());
TextView destinationText = (TextView) itemView.findViewById(R.id.item_destinationTextView);
destinationText.setText(currentStop.getDestination());
TextView timeText = (TextView) itemView.findViewById(R.id.item_timeTextView);
timeText.setText(currentStop.getSchedule());
return itemView;
}
}
}
fragment_list.xml:
<FrameLayout
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="com.example.msa_m.listsstops.ListFragment"
android:id= "#+id/fragment_container"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT DU LAYOUT FRAGMENT"
android:id="#+id/textView"
android:layout_gravity="center_horizontal|top" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/stopsList"
android:layout_alignParentEnd="true"
/>
</FrameLayout>
item_view.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"
android:id ="#+id/my_list_item">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/item_icon"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:src="#drawable/green_bus"
android:maxWidth="80dp"
android:minHeight="80dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Nom de l'arret"
android:id="#+id/item_nameTextView"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/item_icon" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Destination"
android:layout_marginTop="5dp"
android:layout_marginStart="10dp"
android:id="#+id/item_destinationTextView"
android:layout_below="#+id/item_nameTextView"
android:layout_toEndOf="#+id/item_icon" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Temps"
android:id="#+id/item_timeTextView"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
</RelativeLayout><?xml version="1.0" encoding="utf-8"?>
But when I run it, this endless load with a ProgressBar in the middle of the screen...
Does someone can help me ?
Ok, since your code works fine for me, heres a modified version of your project.
Your Activity Layout could probably look like:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Then, in your activity, you just inflate the activity layout and replace the container with your fragment:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListFragment listFragment = new ListFragment();
listFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentContainer, listFragment)
.commit();
}
}
And your fragment takes care of inflating the list ui and managing all the data:
public class ListFragment extends Fragment{
ListView listView;
ArrayAdapter<stops> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<stops> mystops = new ArrayList<>();
mystops.add(new stops("Corum", "Odysseum", "5min", R.drawable.green_tram));
mystops.add(new stops("Corum", "Mosson", "2min", R.drawable.orange_tram));
mystops.add(new stops("Corum", "Saint-Jean de Vedas", "1min", R.drawable.red_tram));
adapter = new myListAdapter(getActivity(), mystops);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
listView = (ListView) view.findViewById(R.id.stopsList);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView.setAdapter(adapter);
}
private static class myListAdapter extends ArrayAdapter<stops> {
public myListAdapter(Context context, ArrayList<stops> stopList) {
super(context, R.layout.item_view, stopList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null)
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_view, parent, false);
stops currentStop = getItem(position);
ImageView imageView = (ImageView)itemView.findViewById(R.id.item_icon);
imageView.setImageResource(currentStop.getIconID());
TextView nameText = (TextView)itemView.findViewById(R.id.item_nameTextView);
nameText.setText(currentStop.getName());
TextView destinationText = (TextView) itemView.findViewById(R.id.item_destinationTextView);
destinationText.setText(currentStop.getDestination());
TextView timeText = (TextView) itemView.findViewById(R.id.item_timeTextView);
timeText.setText(currentStop.getSchedule());
return itemView;
}
}
How do i set a text field in Eclipse to work in conjunction with an item selected in a Spinner? EXAMPLE- If the user selects the second item (out of lets say 3 in the drop down menu) i want them to be able to use the text field to the fight of the spinner to set a value to that item selected. Think of it like a translation tool. If the person selects English out of the menu of languages and then types in an english word (in the text field) i want it to be able to CONVERT that to whatever they chose in the second spinner (Spanish) once they hit the "convert" button.
I apologize if this question seems more in need of a java/eclipse lesson then code help, but i appreciate any help at all :)
MainActivity
package com.overworldinnovations.datatool;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.os.Build;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Spinner spinner1, spinner2;
private Button buttonConvert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
//List<String> list = new ArrayList<String>();
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner2.setOnItemSelectedListener(new CustomOnItemSelectedListener());
/*list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);*/
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).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.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.overworldinnovations.datatool.MainActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonConvert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:text="Convert" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Please Select A Data Type To Be Converted"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner1"
android:layout_marginTop="45dp"
android:entries="#array/type_arrays"
android:prompt="#string/data_prompt" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="60dp"
android:entries="#array/type_arrays"
android:prompt="#string/data_prompt" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/spinner2"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="numberSigned" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner1"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="numberSigned" />
</RelativeLayout>
strings
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Data Tool</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="convert">Convert</string>
<string name="data_tool_is_an_application_that_converts_binary_to_decimal_d">Data Tool is an application that converts Binary to Decimal :D</string>
<string name ="data_prompt">Choose a data type</string>
<string-array name = "type_arrays">
<item >Decimal</item>
<item >Binary</item>
<item >Hexidecimal</item>
</string-array>
</resources>
CustomOnItemSelectedListener
package com.overworldinnovations.datatool;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Well, i cannot tell you about your conversion thingy but i will tell you how to listen to do something based on a selected spinner entry and how to manipulate textfields. The rest you have to code :-)
Here comes a class that implements a spinner, and does something based on the selected option in the spinner. It can be made very different too but this should explain things easy.
public class MyClass extends Fragment implements AdapterView.OnItemSelectedListener {
// Your Spinner
public Spinner spinner;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
final View view = inflater.inflate(R.layout.tab2, container, false);
// Customize from here
final TextView textview = (TextView) view.findViewById(R.id.textView);
final Button button = (Button) view.findViewById(R.id.btn_calculate);
setSpinnerContent( view );
// attach an OnClickListener
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Integer selectedOption = spinner.getSelectedItemPosition();
if (selectedOption==0) {
myString = "Option 1 selected";
}
if (selectedOption==1) {
myString = "Option 2 selected";
}
if (selectedOption==2) {
myString = "Option 3 selected";
}
textview.setText(myString);
}
}
);
return view;
}
private void setSpinnerContent( View view )
{
spinner = (Spinner) view.findViewById( R.id.spinner );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter( adapter );
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // ItemsSelected
//An alternate way to listen to the selected items
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
The spinner gets content from an String XML resource like this:
<string-array name="planets_array">
<item>Euro</item>
<item>US-Dollar</item>
<item>Yen</item>
</string-array>
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String val = spinner.getSelectedItem().toString();//Getting Value of Selected Item
txtPerc.setText(val);//TextView
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
Do Something Like This.. And please Clear Your Question.
Hope Its Help..
I am new to android apps development,
I want to get edittext value which present outside the listview, and I want to get value inside OnItemClick. when user enter text and click list item I need to get both list item selected and edittext text value.
I Created main layout containing one edittext and listview. I want to get edittext value in listview OnItemClick event.
I tried I can't get it. Please guide me.
Here I list out my sample program.
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
ArrayList<String> listVal = new ArrayList<String>();
public EditText searchKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchKey = (EditText) findViewById(R.id.searchKey);
ListView spinner = (ListView) findViewById(R.id.listView1);
listVal.add("Apple");
listVal.add("Avocado");
listVal.add("Banana");
listVal.add("Blueberry");
listVal.add("Coconut");
listVal.add("Durian");
listVal.add("Guava");
listVal.add("Kiwifruit");
listVal.add("Jackfruit");
ListAdapter listAdapter = new ListAdapter(getApplicationContext(), R.layout.list, listVal);
spinner.setAdapter(listAdapter);
spinner.setOnItemClickListener(listAdapter);
}
}
ListAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ListAdapter extends ArrayAdapter<String> implements OnItemClickListener {
private final Context context;
private final ArrayList<String> values;
int layoutResourceId;
public ListAdapter(Context context, int layoutResourceId, ArrayList<String> values) {
super(context, layoutResourceId, values);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.values = values;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(layoutResourceId, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.listItem);
textView.setText(values.get(position));
return rowView;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView message = (TextView)arg1.findViewById(R.id.listItem);
Toast.makeText(context, message.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
activity_main.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/searchKey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10" >
<requestFocus />
</EditText>
<ListView
android:id="#+id/listView1"
android:layout_below="#+id/searchKey"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" >
</ListView>
</RelativeLayout>
list.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="vertical" >
<TextView
android:id="#+id/listItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dip"
android:textColor="#000000" />
</LinearLayout>
you can use this also, it may help some others..
spinner.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos,
long id) {
// TODO Auto-generated method stub
int p = values.get(pos);
String key = searchKey.getText().toString().trim();
Log.v("listitem_value",p);
Log.v("EditTextValue",key);
Toast.makeText(context, "listitem_value:"+p+"\nEditTextValue:"+key, Toast.LENGTH_SHORT).show();
}
});
Try this..
public class MainActivity extends Activity {
ArrayList<String> listVal = new ArrayList<String>();
public EditText searchKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchKey = (EditText) findViewById(R.id.searchKey);
ListView spinner = (ListView) findViewById(R.id.listView1);
listVal.add("Apple");
listVal.add("Avocado");
listVal.add("Banana");
listVal.add("Blueberry");
listVal.add("Coconut");
listVal.add("Durian");
listVal.add("Guava");
listVal.add("Kiwifruit");
listVal.add("Jackfruit");
ListAdapter listAdapter = new ListAdapter(getApplicationContext(), R.layout.list, listVal);
spinner.setAdapter(listAdapter);
spinner.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos,
long id) {
// TODO Auto-generated method stub
Log.v("listitem_value",values.get(pos));
Log.v("EditTextValue",searchKey.getText().toString().trim());
Toast.makeText(context, "listitem_value:"+values.get(pos)+"\nEditTextValue:"+searchKey.getText().toString().trim(), Toast.LENGTH_SHORT).show();
}
});
}
}
and also remove implements OnItemClickListener and onItemClick method in ListAdapter
spinner.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos,
long id) {
// TODO Auto-generated method stub
TextView message = (TextView)arg1.findViewById(R.id.listItem);
Toast.makeText(context, message.getText().toString(), Toast.LENGTH_SHORT).show();
Log.v("EditText",searchKey.getText().toString().trim());
}
});