I am making a app that users autocompleteTextview.
which suggest suggestion from server when user type anything by addTextChangedListener
but many times user may be not select suggestion and type directly and move
But i want that user only select suggested items.
Output
After click on remove button
i have implement this same in my previous project i have create demo for your try this:
XML file
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.user31.demosforstack.AutocomplateTextVIew">
<AutoCompleteTextView
android:id="#+id/autoComplateText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search here" />
</LinearLayout>
JAVA file
package com.example.user31.demosforstack;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import java.util.ArrayList;
public class AutocomplateTextVIew extends AppCompatActivity {
AutoCompleteTextView autoComplateText;
ArrayAdapter arrayAdapter;
ArrayList<String> arrayList;
boolean isSelect = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_autocomplate_text_view);
arrayList = new ArrayList();
for (int i = 0; i < 10; i++) {
arrayList.add("item " + i);
}
autoComplateText = findViewById(R.id.autoComplateText);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, arrayList);
autoComplateText.setAdapter(arrayAdapter);
autoComplateText.setThreshold(2);
autoComplateText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) parent.getAdapter().getItem(position);
isSelect = true;
autoComplateText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.remove, 0);
Log.e("Item: ", item);
autoComplateText.setInputType(InputType.TYPE_NULL);
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(autoComplateText.getWindowToken(), 0);
}
});
autoComplateText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int DRAWABLE_RIGHT = 2;
if (event.getAction() == MotionEvent.ACTION_UP) {
if (autoComplateText != null){
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(autoComplateText.getWindowToken(), 0);
if (event.getRawX() >= (autoComplateText.getRight() - autoComplateText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
autoComplateText.setText("");
autoComplateText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
isSelect = false;
return true;
}
}
}
return false;
}
});
}
}
Related
hello guys i started to learn to build android applications via udacy. After a long troubleshooting i didnt find something that can cause the bug that i have. the bug is that when i rotate the phone the view seems to clone it self and not deleting the previous one if someone can help me ill be very happy.
1) normal state of app:
2) after rotation:
3) and after another rotation the application crashing
it never happend until i added the code in the xml file of the view:
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for weather forecast list item for future day (not today) -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/list_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/list_item_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tomorrow"/>
<TextView
android:id="#+id/list_item_forecast_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:gravity="right">
<TextView
android:id="#+id/list_item_high_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="81"
android:paddingLeft="10dp"/>
<TextView
android:id="#+id/list_item_low_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="68"
android:paddingLeft="10dp"/>
</LinearLayout>
</LinearLayout>
Activity Code:
package com.example.andy.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private String FORECASTFRAGMENT_TAG = "FFTAG";
String mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new MainActivityFragment(), FORECASTFRAGMENT_TAG)
.commit();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mLocation = Utility.getPreferredLocation(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
String location = Utility.getPreferredLocation(this);
if(location != null && location != mLocation){
MainActivityFragment ff = (MainActivityFragment)getSupportFragmentManager().findFragmentById(R.id.fragment);
if(ff != null){
ff.onLocationChanged();
}
mLocation = location;
}
}
#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){
Intent settings = new Intent(this,SettingsActivity.class);
startActivity(settings);
}
if(R.id.action_map == id){
openPreferedLocationMap();
}
return super.onOptionsItemSelected(item);
}
private void openPreferedLocationMap(){
String location = Utility.getPreferredLocation(this);
Uri geoLocation = Uri.parse("geo:0,0?").buildUpon().appendQueryParameter("q",location).build();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if(intent.resolveActivity(getPackageManager()) != null){
startActivity(intent);
}
else{
Log.d("SHOWING MAP PROBLEMM","could't call"+ location+ "intent");
}
}
}
Fragment Code:
package com.example.andy.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.andy.sunshine.app.data.WeatherContract;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int FORECAST_LOADER = 0;
// For the forecast view we're showing only a small subset of the stored data.
// Specify the columns we need.
private static final String[] FORECAST_COLUMNS = {
// In this case the id needs to be fully qualified with a table name, since
// the content provider joins the location & weather tables in the background
// (both have an _id column)
// On the one hand, that's annoying. On the other, you can search the weather table
// using the location set by the user, which is only in the Location table.
// So the convenience is worth it.
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
WeatherContract.WeatherEntry.COLUMN_DATE,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.LocationEntry.COLUMN_COORD_LAT,
WeatherContract.LocationEntry.COLUMN_COORD_LONG
};
// These indices are tied to FORECAST_COLUMNS. If FORECAST_COLUMNS changes, these
// must change.
static final int COL_WEATHER_ID = 0;
static final int COL_WEATHER_DATE = 1;
static final int COL_WEATHER_DESC = 2;
static final int COL_WEATHER_MAX_TEMP = 3;
static final int COL_WEATHER_MIN_TEMP = 4;
static final int COL_LOCATION_SETTING = 5;
static final int COL_WEATHER_CONDITION_ID = 6;
static final int COL_COORD_LAT = 7;
static final int COL_COORD_LONG = 8;
private ForecastAdapter mForecastAdapter;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#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_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// The CursorAdapter will take data from our cursor and populate the ListView.
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
Intent intent = new Intent(getActivity(), DetailActivity.class)
.setData(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
locationSetting, cursor.getLong(COL_WEATHER_DATE)
));
startActivity(intent);
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(FORECAST_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
private void updateWeather() {
FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity());
String location = Utility.getPreferredLocation(getActivity());
weatherTask.execute(location);
}
public void onLocationChanged(){
updateWeather();
getLoaderManager().restartLoader(FORECAST_LOADER,null,this);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String locationSetting = Utility.getPreferredLocation(getActivity());
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
locationSetting, System.currentTimeMillis());
return new CursorLoader(getActivity(),
weatherForLocationUri,
FORECAST_COLUMNS,
null,
null,
sortOrder);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mForecastAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mForecastAdapter.swapCursor(null);
}
}
And Class That Extends CursorAdapter "ForecastAdapter":
package com.example.andy.sunshine.app;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.andy.sunshine.app.data.WeatherContract;
/**
* {#link ForecastAdapter} exposes a list of weather forecasts
* from a {#link android.database.Cursor} to a {#link android.widget.ListView}.
*/
public class ForecastAdapter extends CursorAdapter {
private final int VIEW_TYPE_TODAY = 0;
private final int VIEW_TYPE_FUTURE_DAY = 1;
public ForecastAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public int getItemViewType(int position) {
return (position == 0)? VIEW_TYPE_TODAY:VIEW_TYPE_FUTURE_DAY;
}
#Override
public int getViewTypeCount() {
return 2;
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(Context context,double high, double low) {
boolean isMetric = Utility.isMetric(mContext);
String highLowStr = Utility.formatTemperature(context,high, isMetric) + "/" + Utility.formatTemperature(context,low, isMetric);
return highLowStr;
}
/*
This is ported from FetchWeatherTask --- but now we go straight from the cursor to the
string.
*/
private String convertCursorRowToUXFormat(Context context,Cursor cursor) {
// get row indices for our cursor
String highAndLow = formatHighLows(context,
cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP),
cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP));
return Utility.formatDate(cursor.getLong(MainActivityFragment.COL_WEATHER_DATE)) +
" - " + cursor.getString(MainActivityFragment.COL_WEATHER_DESC) +
" - " + highAndLow;
}
/*
Remember that these views are reused as needed.
*/
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int VIEW_TYPE = getItemViewType(cursor.getPosition());
int layoutId = -1;
if(VIEW_TYPE == VIEW_TYPE_TODAY){
layoutId = R.layout.list_item_forecast_today;
}else if(VIEW_TYPE == VIEW_TYPE_FUTURE_DAY){
layoutId = R.layout.list_item_forecast;
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
view.setTag(viewHolder);
return view;
}
/*
This is where we fill-in the views with the contents of the cursor.
*/
#Override
public void bindView(View view, Context context, Cursor cursor) {
// our view is pretty simple here --- just a text view
// we'll keep the UI functional with a simple (and slow!) binding.
MyViewHolder viewHolder = (MyViewHolder)view.getTag();
viewHolder.iconView.setImageResource(R.mipmap.ic_launcher);
// TODO Read date from cursor
long dateInMillis = cursor.getLong(MainActivityFragment.COL_WEATHER_DATE);
viewHolder.dateView.setText(Utility.getFriendlyDayString(context, dateInMillis));
// TODO Read weather forecast from cursor
viewHolder.descriptionView.setText(cursor.getString(MainActivityFragment.COL_WEATHER_DESC));
// Read user preference for metric or imperial temperature units
boolean isMetric = Utility.isMetric(context);
// Read high temperature from cursor
double high = cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP);
viewHolder.highTempView.setText(Utility.formatTemperature(context,high, isMetric));
// TODO Read low temperature from cursor
double low = cursor.getDouble(MainActivityFragment.COL_WEATHER_MIN_TEMP);
viewHolder.lowTempView.setText(Utility.formatTemperature(context,low, isMetric));
}
public static class MyViewHolder {
public final ImageView iconView;
public final TextView dateView;
public final TextView descriptionView;
public final TextView highTempView;
public final TextView lowTempView;
public MyViewHolder(View view){
iconView = (ImageView) view.findViewById(R.id.list_item_icon);
dateView = (TextView)view.findViewById(R.id.list_item_date_textview);
descriptionView = (TextView)view.findViewById(R.id.list_item_forecast_textview);
highTempView = (TextView)view.findViewById(R.id.list_item_high_textview);
lowTempView = (TextView)view.findViewById(R.id.list_item_low_textview);
}
}
}
if you want to see the whole project and check maybe for errors that may cause that i posting here my github https://github.com/obruchkov/Sunshine with all the code that i did. please help me guys
Pageviewer.java code:
//hide status bar/action bar on single tap
package com.app.imageswiper;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Pageviwer extends AppCompatActivity {
private Integer[] mImageIds = {R.drawable.page001, R.drawable.page002,
R.drawable.page003};
private static final String DEBUG_TAG = "pageviwer ";
ImageView imageView;
float startXValue = 1;
public int num;
public int click;
protected static final String TAG = "Pageviwer";
private GestureDetector mGestureDetector;
public SharedPreferences prefs;
public static int Bookmark = 0;
public static int Pageno = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int Bookmark1 = prefs.getInt("Bookmark", 0);
Bookmark = Bookmark1;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int Pageno1 = prefs.getInt("Pageno", 0);
Pageno = Pageno1;
setContentView(R.layout.pageviwer);
imageView = (ImageView) findViewById(R.id.image_place_holder);
imageView.setImageResource(mImageIds[0]);
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
setupGestureDetector();
hideActionBar(); // hide action bar after 1 second
}
private void setupGestureDetector() {
mGestureDetector = new GestureDetector(this,
new GestureDetector.SimpleOnGestureListener() {
//Detecting Swipe/Fling Direction
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
Log.i(TAG, "onFling");
if (e1.getX() < e2.getX()) {
Log.d(TAG, "Left to Right swipe performed");
if (num == 2) {
num = num;
} else {
imageView.setImageResource(mImageIds[num + 1]);
num = num + 1;
}
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
}
if (e1.getX() > e2.getX()) {
Log.d(TAG, "Right to Left swipe performed");
if (num == 0) {
num = num;
} else {
imageView.setImageResource(mImageIds[num - 1]);
num = num - 1;
}
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
}
return true;
}
//detecting single tap
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.i(TAG, "onSingleTapUp");
Toast.makeText(getApplicationContext(), "Single Tap ", Toast.LENGTH_LONG).show();
//Remove notification bar and action bar
if (click == 0) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
if (getSupportActionBar() != null) getSupportActionBar().hide();
click = 1;
}
//Return notification bar and action bar
else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
if (getSupportActionBar() != null) getSupportActionBar().show();
click = 0;
}
return true;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (mGestureDetector != null) {
return mGestureDetector.onTouchEvent(event);
} else {
return super.onTouchEvent(event);
}
}
public void hideActionBar() {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// DO DELAYED STUFF
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
if (getSupportActionBar() != null) getSupportActionBar().hide();
click = 1;
}
}, 1000); // 1000 milliseconds (1 second)
}
#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 == com.app.imageswiper.R.id.action_settings) {
Bookmark=1;
prefs.edit().putInt("Bookmark", Bookmark).commit();
prefs.edit().putInt("Pageno", num).commit();
Toast.makeText(getApplicationContext(), "Bookmark value is "+Bookmark, Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
ViewPagerAdapter code:
package com.app.imageswiper;
/**
* Created by Jaffer on 14-Apr-16.
*/
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class Bookmarks extends Fragment {
public SharedPreferences prefs;
public static int Bookmark = 0;
public static int Pageno = 0;
Button sendButton = null;
View inflatedView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int Bookmark1 = prefs.getInt("Bookmark", 0);
Bookmark = Bookmark1;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int Pageno1 = prefs.getInt("Pageno", 0);
Pageno = Pageno1;
this.inflatedView = inflater.inflate(R.layout.bookmarks, container, false);
sendButton = (Button) inflatedView.findViewById(R.id.bookmark);
if(Bookmark==1){sendButton.setText("Page "+Pageno);}
else {sendButton.setText("No Bookmark ");}
if(sendButton == null)
{
Log.d("debugCheck", "HeadFrag: sendButton is null");
return inflatedView;
}
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Pageviwer.class);
startActivity(intent);
}
});
return inflatedView;
}
}
bookmarks.xml code:
<?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"
android:id="#+id/bookmarks">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/bookmark"
android:layout_alignParentBottom="true" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
</LinearLayout>
I don't know how to update the button text from Pageviewer.java for the button with R.id.bookmark that shows up on the Bookmarks fragment on the click of menu item R.id.action_settings. I want to do this so that the button text corresponds to the page that is being bookmarked. I tried alot of things but to no avail. Can someone please help me with anything?
Thanks in advance
Create a method in your fragment to update the text of your button.
public void updateText(String newText){
//assuming button is globally declared in your fragment.
button.setText(newText);
}
Instead of Gesture Detector you could use a ViewPager which supports swiping to the left and right.You can find a sample implementation here.
Then in your Activty,implement PageChanegListener on ViewPager.
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.You have to implement viewpager's adapter with getItem(index) which returns a fragment at that index.
BookMarkFragment fragment (BookMarkFragment)mAdapter.getItem(position);
fragment.updateText(newText);
};
});
You should save the state of a button somewhere. Your field int Bookmark == 0, so expression sendButton.setText("Page "+Pageno); never execute. Save the state in SharedPreferences and get this state. Like this:
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int isBookmark = prefs.getInt("Bookmark", 0);
int mPageno = prefs.getInt("Pageno", 0);
...
if(isBookmark == 1){
sendButton.setText("Page " + mPageno);
} else {
sendButton.setText("No Bookmark");
}
in my code I am reading from a database, i am also using a custom adapter to print out each row, in the row there is a texttview, 2 buttons and a edittext. This all works fine but when a button is pressed the edittext is incremented or decremented, is there a way to change my code so that each edittext is separate to the row above or below it? As in when i click a button on one row the edittext will change to two and when i click a button in another row the counter wont carry from the first row to the second.
this is the custom adapter
package com.example.rory.dbtest;
/**
* Created by Rory on 02/11/2014.
*/
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.pinchtapzoom.R;
public class CustomCursorAdapter extends CursorAdapter{
public int counter = 0;
private MyAdapterInterface mMyInterface;
public CustomCursorAdapter(Context context, Cursor c, MyAdapterInterface myInterface) {
super(context, c);
this.context = context;
this.mMyInterface = myInterface;
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.item1);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final EditText edit1 = (EditText) view.findViewById(R.id.runningTotal);
Button plusButton = (Button) view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++;
edit1.setText(Integer.toString(counter));
mMyInterface.updateEditText(counter);
}
});
final Button minusButton = (Button) view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter--;
edit1.setText(Integer.toString(counter));
mMyInterface.updateEditText(counter);
}
});
}
}
this is the main activity
package com.example.rory.dbtest;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.pinchtapzoom.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
public class MyActivity extends Activity implements MyAdapterInterface{
private CustomCursorAdapter customAdapter;
public ListView list1;
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
public MyActivity mMyActivity;
//public EditText TotalCost;
//public EditText TotalLitres;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
mMyActivity = this;
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, addassignment.class);
startActivity(i);
}
});
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Handler().post(new Runnable() {
#Override
public void run() {
//Log.d("test", "customadapter is " + customAdapter.toString());
//Log.d("test", "databaseHelper is " + databaseHelper.toString());
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
list1.setAdapter(customAdapter);
}
});
}
public void updateEditText(int value)
{
EditText myEditText = (EditText)findViewById(R.id.edit1);
EditText myEditText2 = (EditText)findViewById(R.id.edit2);
myEditText.setText(String.valueOf(value));
myEditText2.setText(String.valueOf(value));
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
And this is my XML row
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="#+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="30sp"
android:paddingBottom="5dp"/>
<Button
android:id="#+id/plusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/plusButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/runningTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/minusButton"
android:layout_toStartOf="#+id/minusButton"
android:layout_marginRight="30dp" />
<Button
android:id="#+id/minusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/minusButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
The problem is that your counter variable is only storing the last value, every time you click the button the new value replaces the old value.
I suggest changing counter from an int to an ArrayList
public ArrayList<Integer> counter;
Be sure to initialize the array in the constructor like so:
public CustomCursorAdapter(Context context, Cursor c, MyAdapterInterface myInterface) {
super(context, c);
this.context = context;
this.mMyInterface = myInterface;
counter = new ArrayList<Integer>();
//default all counters to 0
for(int i=0; i<cursor.getCount(); i++)
{
counter.add(0);
}
}
Change the click listeners to look like this:
plusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos;
public void onClick(View v) {
counterPos = counter.get(cursor.getPosition())
counterPos--;
counter.set(cursor.getPosition(), counterPos);
edit1.setText(Integer.toString(counterPos));
mMyInterface.updateEditText(counterPos);
}
});
minusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos;
public void onClick(View v) {
counterPos = counter.get(cursor.getPosition())
counterPos++;
counter.set(cursor.getPosition(), counterPos);
edit1.setText(Integer.toString(counterPos));
mMyInterface.updateEditText(counterPos);
}
});
Explanation
counterPos = counter.get(cursor.getPosition())
cursor.getPosition() will return the current row position in the list. We will use this position number to identify the position in the ArrayList where we store the associated counter value. We get the current value of this counter and store it in the variable counterPos.
counterPos++;
counter.set(cursor.getPosition(), counterPos);
We increment/decrement the value and then set the associated array Position to this new value
edit1.setText(Integer.toString(counterPos));
mMyInterface.updateEditText(counterPos);
You can then reuse this variable for display purpose as above
This is my first StackOverFlow answer, I hope I have helped! :)
Any troubles just let me know.
Good luck,
Hugh.
I am googling for the last few hours, I've seen this question asked like 20 times but none of the solutions seem to work for me. I have a ListView and a CustomList class, that incorporates a list adapter and a simple dialog for editing/removing/renaming items. everything works as supposed until the first screen rotation. After that, the list stops being updated, although the adapter contains all the right data.
I will post both files without skipping a line. I don't need any data being saved at this time, I will handle that later. This is really weird because supposedly the application gets completely restarted after screen rotation. What makes it even stranger, the dummy items are added onCreate even after screen rotation, but after that there is no other response from the list.
Please excuse my english and my noobness and try to point me in the right direction.
package com.sl.mylandmarks;
import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView;
public class MainActivity extends Activity {
Button addButton; ListView landmarksList; EditText inputName, inputSearch; CustomList customList; Context globalContext; TextView gpsState; private LocationManager locationManager; private GPSTracker gpsTracker; private double longitude; private double latitude;
#Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
gpsTracker = new GPSTracker(MainActivity.this);
globalContext = this;
addButton = (Button) findViewById(R.id.addBtn);
customList = new CustomList(this);
landmarksList = (ListView) findViewById(R.id.listView1); landmarksList.setAdapter(customList.getAdapter()); landmarksList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); landmarksList.setTextFilterEnabled(true); landmarksList.setLongClickable(true); customList.theList = landmarksList;
inputName = (EditText) findViewById(R.id.EditItemName);
gpsState = (TextView) findViewById(R.id.gpsState);
ContentResolver contentResolver = getBaseContext().getContentResolver(); boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER); if (gpsStatus) { gpsState.setText("GPS Enabled"); } else { gpsState.setText("GPS Disabled"); }
// // SEARCH BOX
inputSearch = (EditText) findViewById(R.id.editText3); inputSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) { }
public void onTextChanged(CharSequence s, int start, int before,
int count) {
customList.getAdapter().getFilter().filter(s); } }); // // SEARCH BOX
// / DUMMY ITEMS customList.addItem("Home", "43.1565 / 15.8645"); customList.addItem("Work", "43.1565 / 15.8645"); customList.addItem("Denis` apartment", "43.1565 / 15.8645"); customList.addItem("Natasa", "43.1565 / 15.8645"); customList.addItem("Bruce Wayne", "43.1565 / 15.8645"); customList.addItem("Walker shop", "43.1565 / 15.8645"); customList.addItem("Chuck Norris Residence", "43.1565 / 15.8645"); customList.addItem("Some landmark", "43.1565 / 15.8645"); // customList.removeItem(3);
OnItemLongClickListener listLongClick = new OnItemLongClickListener() {
#Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
customList.showOptionsDialog(arg2);
return true;// event consumed, not dispatched forward } };
landmarksList.setOnItemLongClickListener(listLongClick);
OnClickListener ButtonClick = new View.OnClickListener() {
#Override public void onClick(View v) {
switch (v.getId()) {
case R.id.addBtn:
customList.addItem(inputName.getText().toString(),
"45.5644 / 23.6541");
inputName.setText("");
break;
}
}
};
addButton.setOnClickListener(ButtonClick);
}
#Override public void onPause() { super.onPause();
}
#Override public void onResume() { super.onResume();
}
#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;
}
}
and CustomList.java
package com.sl.mylandmarks;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class CustomList {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(
2);
HashMap<String, String> maplist;
SimpleAdapter listAdapter;
public Context context;
public ListView theList;
public CustomList(Context con) {
context = con;
String[] from = { "line1", "line2" };
int[] to = { android.R.id.text1, android.R.id.text2 };
listAdapter = new SimpleAdapter(context, list,
android.R.layout.simple_list_item_2, from, to);
}
public void addItem(String name, String coords) {
if ((name != null) && (name.length() != 0)) {
maplist = new HashMap<String, String>();
maplist.put("line1", name);
maplist.put("line2", coords);
list.add(maplist);
listAdapter.notifyDataSetChanged();
}
}
public void removeItem(int id) {
Log.d("removing",list.remove(id).toString());
listAdapter.notifyDataSetChanged();
}
public void renameItem(int id, String newName) {
Log.d("SL","Rename Selected");
maplist = new HashMap<String, String>();
maplist.put("line1", newName);
maplist.put("line2", list.get(id).get("line2"));
list.set(id, maplist);
listAdapter.notifyDataSetChanged();
}
public SimpleAdapter getAdapter() {
return listAdapter;
}
public void showOptionsDialog(final int position) {
//Log.d("SL", String.valueOf(position));
final Dialog optionsDialog = new Dialog(context);
optionsDialog.setContentView(R.layout.list_dialog);
optionsDialog.setTitle("Options");
optionsDialog.show();
final EditText itemNameEdit = (EditText) optionsDialog
.findViewById(R.id.EditItemName);
final Button removeBtn = (Button) optionsDialog
.findViewById(R.id.removeBtn);
final Button renameBtn = (Button) optionsDialog
.findViewById(R.id.renameBtn);
final Button cancelBtn = (Button) optionsDialog
.findViewById(R.id.cancelBtn);
itemNameEdit.setText(list.get(position).get("line1"));
itemNameEdit.setSelection(itemNameEdit.length());
OnClickListener ButtonClick = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.removeBtn:
removeItem(position);
optionsDialog.dismiss();
break;
case R.id.renameBtn:
renameItem(position, itemNameEdit.getText().toString());
optionsDialog.dismiss();
break;
case R.id.cancelBtn:
optionsDialog.dismiss();
break;
}
}
};
removeBtn.setOnClickListener(ButtonClick);
renameBtn.setOnClickListener(ButtonClick);
cancelBtn.setOnClickListener(ButtonClick);
}
}
I not sure what exactly is your question. And I didn't look at your code, because I don't think that SO is a good place to just dump classes and say "fix this". But I might have an answer for you.
It is true that Android is recreating the activity when you rotate (like roky says). If you come from an iPhone development background (which is my case), it look like kind of weird.
But if your activity is not too complex, you can say to Android to handle it. Do to this, add this to your tag of your AndroidManifest.xml
<activity android:configChanges="orientation|screenSize" ... >
</activity>
Here is a better explanation than mine : android:configChanges="orientation" does not work with fragments
If my answer was the good one, it would be nice to accept it!
I just started with Android programming and here's the thing.
How can i check if the item in GridView was already clicked? Something like assigning a boolean 'clicked' for EACH item in Grid and changing it's value every time i click the item.
Currently i'm just using an array of bools so if i click item[x] it switches the bool[x] and then i do the check if it's true/false and modify the item accordingly, but there has to be a neater way of doing the same!
My code:
package com.example.mojrecnik;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class Glavna extends Activity implements AdapterView.OnItemClickListener {
private static final int LENGTH_SHORT = 0;
GridView grid;
TextView tekst;
String[] izfajla = new String[200];
String[] izfajla2 = new String[200];
boolean[] kliknutmrs = new boolean[200];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glavna);
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(new MojAdapter());
grid.setOnItemClickListener(this);
//tekst=(TextView)findViewById(R.id.tekst);
citaFajl();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_glavna, menu);
return true;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView klik = (TextView)arg1.findViewById(R.id.gridtekst2);
if(kliknutmrs[arg2]) {
kliknutmrs[arg2]=!kliknutmrs[arg2];
klik.setText(izfajla[arg2]); }
else {
kliknutmrs[arg2]=!kliknutmrs[arg2];
klik.setText(izfajla2[arg2]); }
}
public void onNothingSelected(AdapterView<?> arg0) {
}
public void citaFajl() {
File kartica = Environment.getExternalStorageDirectory();
File fajl = new File(kartica, "reci.txt");
StringBuilder tekst = new StringBuilder();
int i=0;
try {
BufferedReader br = new BufferedReader(new FileReader(fajl));
String linija;
String[] prva;
while ((linija = br.readLine())!=null) {
prva = linija.split("-");
izfajla[i]=prva[0];
if(prva[1].length()>0)
izfajla2[i]=prva[1];
i++;
}
}
catch (IOException e) {
Toast greska = Toast.makeText(this, e.getMessage().toString(), LENGTH_SHORT);
greska.show();
}
}
private class MojAdapter extends ArrayAdapter {
public MojAdapter() {
super(Glavna.this, R.layout.gridvju, izfajla);
}
public View getView(int position, View convertView, ViewGroup parent) {
//vazno!! pravim vju od inflatera i vracam vju a ne convertvju!
View gridvju;
if(convertView==null) {
LayoutInflater inflater = getLayoutInflater();
gridvju = inflater.inflate(R.layout.gridvju, parent, false);
}
else
gridvju=convertView;
TextView tekst2 = (TextView)gridvju.findViewById(R.id.gridtekst2);
tekst2.setLines(2);
tekst2.setText(izfajla[position]);
return(gridvju);
}
}
}
And XML(main):
<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" >
<!--
<TextView
android:id="#+id/tekst"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="20dp"
android:layout_below="#id/tekst" >
</TextView> -->
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:horizontalSpacing="#dimen/padding_medium"
android:numColumns="3"
android:stretchMode="columnWidth" >
</GridView>
</RelativeLayout>
And layout:
<?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="wrap_content"
android:orientation="vertical" >
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/gridtekst2" />
</LinearLayout>
Here is how i worked it in the end. I created a custom class to contain text which is displayed and also added a bool in there so now every element in my gridview has its own 'click-checker'.
note: this program simply alternates between 2 words onClick, if you wanna try it use text file with data formated 'word1 - word2'
Code:
package com.example.mojrecnik;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
public class Glavna extends Activity implements AdapterView.OnItemClickListener {
private static final int LENGTH_LONG = 1;
GridView grid;
List<Rec> lReci = new ArrayList<Rec>(); //this is our list of data which contains text and bool check
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glavna);
citaFajl();
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(new MojAdapter());
grid.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_glavna, menu);
return true;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
VjuHolder holder=(VjuHolder)arg1.getTag();
if(!lReci.get(arg2).clicked)
holder.text.setText(lReci.get(arg2).rec2);
else
holder.text.setText(lReci.get(arg2).rec1);
lReci.get(arg2).clicked = !lReci.get(arg2).clicked;
}
public void onNothingSelected(AdapterView<?> arg0) {
//////////////////////////////////////////
}
public void citaFajl() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(Environment.getExternalStorageDirectory(), "reci.txt")));
String[] reci = new String[2];
String linija;
Rec rec;
while ((linija = br.readLine()) != null) {
reci = linija.split("-"); //because data in my file is formatted 'word1 - word2', we separate them now so we can alternate between them
reci[1]=reci[1].trim();
rec = new Rec(reci[0], reci[1], false);
lReci.add(rec);
}
}
catch (IOException e) {
Toast.makeText(this, e.getMessage().toString(), LENGTH_LONG).show();
}
}
private class MojAdapter extends ArrayAdapter<String> {
public MojAdapter() {
super(Glavna.this, R.layout.gridvju);
}
public int getCount() {
return lReci.size(); //here we explicitly set the total number of grid elements so it doesn't go out of index range
}
public View getView(int position, View convertView, ViewGroup parent) {
VjuHolder holder;
if(convertView==null) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.gridvju, parent, false);
holder = new VjuHolder();
holder.text = (TextView)convertView.findViewById(R.id.gridtekst2);
convertView.setTag(holder); }
else
holder=(VjuHolder)convertView.getTag();
if(lReci.get(position).clicked) //check to make grid update according to the clicked state of our elements [when scrolling]
holder.text.setText(lReci.get(position).rec2);
else
holder.text.setText(lReci.get(position).rec1);
holder.text.setLines(2);
return(convertView);
}
}
}
//holder class
class VjuHolder {
TextView text;
}
//here we put the text to be displayed along with bool to check in which state is the clicked element
class Rec {
String rec1, rec2;
boolean clicked;
Rec(String rec, String druga, boolean klik) {
rec1 = rec;
rec2 = druga;
clicked = klik;
}
}
There's no such thing like "click history" retained. If user taps anything then, if there's onClickListener assigned, you will get notified about that tap. But you cannot check that by querying UI objects. Boolean array is ok, but I'd use List or ArrayList instead and simply add id of tapped items in my onClickListener.
There is no way to find out whether button was clicked before or not. I think you've been looking for some sort of class property like
if(button.wasOnceClicked){ //THERE IS NO CODE LIKE THIS
}
Am I right? Well, Button class dont have this.
However u can create subclass of Button and add that property and also add some code which will handle that property.
First of all initialize your boolean array in onCreate as:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(new MojAdapter());
grid.setOnItemClickListener(this);
// HERE I have initialized with true valuse
for(int i=0; i<kliknutmrs.length; i++) {
kliknutmrs[i] = true;
}
//tekst=(TextView)findViewById(R.id.tekst);
citaFajl();
}
Then at onClick, just ckeck that the boolean array hav "true" value; so make that position value "false" and same time invert the text value with another String[] array.
At second time it will goto to else part:
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView klik = (TextView)arg1.findViewById(R.id.gridtekst2);
if(kliknutmrs[arg2]) {
System.out.println(" ------------ 11111111111 -----------");
kliknutmrs[arg2]=!kliknutmrs[arg2];
klik.setText(izfajla2[arg2]); }
else {
System.out.println(" ------------- 222222222 -----------");
// NO NEED //kliknutmrs[arg2]=!kliknutmrs[arg2];
klik.setText(izfajla2[arg2]); }
}